在C中键入命名空间
我已经在SO中读到了C中定义类型的不同命名空间,例如,Structs和Unions有一个命名空间,typedef有一个命名空间。
命名空间是这个的确切名称吗? C中存在多少个命名空间?
见6.2.3
来自http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
6.2.3标识符的名称空间
If more than one declaration of a particular identifier is visible at any point in a translation unit, the syntactic context disambiguates uses that refer to different entities. Thus, there are separate name spaces for various categories of identifiers, as follows: — label names (disambiguated by the syntax of the label declaration and use); — the tags of structures, unions, and enumerations (disambiguated by following any32) of the keywords struct, union, or enum); — the members of structures or unions; each structure or union has a separate name space for its members (disambiguated by the type of the expression used to access themember via the . or -> operator); — all other identifiers, called ordinary identifiers (declared in ordinary declarators or as enumeration constants).
我不确定“名称空间”在这里是否是正确的词,但我想我知道你的意思。
你可以做
union name1 { int i; char c; }; struct name2 { int i; char c; }; enum name3 { A, B, C }; typedef int name4; int name5;
这里name1
, name2
和name3
位于不同的“名称空间”(我现在将保留该单词),因为它们不会相互冲突。
这意味着使用它们需要在使用前添加相应的关键字:
struct name1 var; // valid name1 var; // invalid
另一方面, name4
和name5
存在于全局“命名空间”中并发生冲突。 所以在拥有typedef int name4;
,您无法定义名称为name4
的变量。
BTW:标签也定义了自己的命名空间。