在 ISO/IEC 9899:2018(C18) 中,6.2.3“标识符的 namespace ”有规定(强调我的):
6.2.3 Name spaces of identifiers
1 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 the member via the . or -> operator);
all other identifiers, called ordinary identifiers (declared in ordinary declarators or as enumeration constants).
32) There is only one name space for tags even though three are possible.
“即使有三种可能”是什么意思。这个“可能”到底是什么?
<小时/>作为实验,我尝试编译以下代码:
#include <stdio.h>
int main()
{
struct foo{
int a;
double b;
float c;
};
enum foo{
Test1,Test2,Test3
};
union foo{
int x;
double y;
float z;
};
return 0;
}
我的错误是:
error: ‘foo’ defined as wrong kind of tag
对于两者,enum
和 union
定义如您所见 here这也证明了只为同一范围内定义的所有 struct
、enum
和 union
标记提供了一个命名空间,就像标准一样描述了它。但是另外两个“可能的” namespace 又如何呢?
我的问题是:
- 为什么标准规定 C 中的结构、枚举和 union 的标签存在三种可能的 namespace ,而实际上它们只有一种(在同一范围内)?
为什么我们不能使用结构体、枚举和 union 的标签的三种可能的 namespace ,尽管标准说它们应该存在?
最佳答案
该标准并未规定结构、 union 和枚举存在单独的 namespace 。它说理论上三种都是可能的,这意味着该语言可以设计为每种都有单独的 namespace 。
该语言可以设计为具有单独的 namespace ,因为标记仅出现在关键字 struct
、union
或 enum
之后,因此编译器总是知道需要哪个 namespace 。
尽管如此,C 开发人员和 C 委员会决定不在语言设计中使用它。该标准的含义是存在一个 namespace ,其中包含结构体、 union 体和枚举的所有标记。
关于c - 为什么标准规定 C 中的结构、枚举和 union 标签有三种可能的 namespace ,而实际上只有一种?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60127170/