gpt4 book ai didi

c - 为什么可以使用 typedef 的名称作为结构成员的名称?

转载 作者:行者123 更新时间:2023-12-03 18:29:15 26 4
gpt4 key购买 nike

我刚刚发现 gccclang接受以下代码:

typedef int blah;
struct s { char blah; };

但是,他们拒绝这样做,因为类型名称被用作标识符:
typedef int blah;
char blah;

这是否意味着 typedef 的名称在结构定义中不可见?不,因为这在 gcc 和 clang 中都有效:
typedef int blah;
struct s { blah blah; }

我正在查看 C99 标准,但找不到任何说明为什么 typedef 名称可以用作结构成员的名称,但不能用作同一范围内变量的名称的任何内容。

有人可以解释为什么会这样吗?引用任何适用的标准将不胜感激。

最佳答案

结构体成员和普通变量在不同的命名空间中。这就是为什么有两个具有相同标识符名称的普通变量会失败,而如果在 struct 成员中使用相同的标识符名称并且普通变量很好。

C 标准定义了不同的命名空间:

6.2.3 Name spaces of identifiers

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).


(最后两个项目符号直接解决了这个问题)

是的, typedef 'ed 标识符与普通标识符共享 namespace 。 6.7.8 Type definitions :

[...] A typedef name shares the same name space as other identifiers declared in ordinary declarators.

关于c - 为什么可以使用 typedef 的名称作为结构成员的名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61504537/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com