为什么C有标签和标识符的单独名称空间?


cppreference开始:

1) Label name space: all identifiers declared as labels.

2) Tag names: all identifiers declared as names of structs, unions and enumerated types.

3) Member names: all identifiers declared as members of any one struct or union. Every struct and union introduces its own name space of this kind.

4) All other identifiers, called ordinary identifiers to distinguish from (1-3) (function names, object names, typedef names, enumeration constants).

这允许像这样的代码(除其他外):

struct Point { int x, y; };
struct Point Point;

这个代码对我来说似乎有点不清楚,因为Point可以引用结构的类型和实例.为标签和其他标识符分别设置名称空间的动机是什么?

最佳答案 提出的实际问题是

What was the motivation behind having separate name spaces for tags and other identifiers?

这只能通过参考标准委员会的基本原理文件来回答,该文件实际上确实解决了这个问题,不过如下:

Pre-C89 implementations varied considerably in the number of separate name spaces maintained. The position adopted in the Standard is to permit as many separate name spaces as can be distinguished by context, except that all tags (struct, union, and enum) comprise a single name space.

(C99 rationale文件,* 6.2.3节)

因此,明确有意识的代码如

struct point { int point; } point = { .point = 0 };
goto point;
point:
return point.point;

是允许的.我对基本原理的解释是,意图是不受限制的,尽管仍然不清楚为什么不同类型的标签没有给出单独的命名空间.这不可能是偶然的,因此委员会中代表的一方或多方必须反对单独的标记命名空间,并且他们设法占上风.这种反对很可能是出于业务而非技术原因.

*据我所知,C2011标准没有理由文件.至少,还没有.

点赞