我在 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
。
顺便说一句:标签也定义了自己的命名空间。