我已经在SO中读到了C中定义类型的不同命名空间,例如: Structs和Unions有一个名称空间,typedef有一个名称空间。
命名空间是否为此的确切名称? C中存在多少名称空间?
答案 0 :(得分:5)
见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).
答案 1 :(得分:2)
我不确定“名称空间”在这里是否是正确的词,但我想我知道你的意思。
你可以做到
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:标签也定义了自己的命名空间。