加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

是一个结构{…};一个类型或一个未命名的变量?

发布时间:2020-12-16 05:42:50 所属栏目:百科 来源:网络整理
导读:在文件范围,以下是类型声明还是未命名变量? struct student_s { char* name; int age; double height; struct student_s* next; }; 如果是类型定义,那么有什么区别: typedef struct student_s { char* name; int age; double height; struct student_s* ne
在文件范围,以下是类型声明还是未命名变量?
struct student_s {
    char* name;
    int age;
    double height;
    struct student_s* next;   
};

如果是类型定义,那么有什么区别:

typedef struct student_s {
    char* name;
    int age;
    double height;
    struct student_s* next;   
};

(背景:请参阅我在Changing a variable from global to local – C的答案,我相信第一个引入了一个未命名的变量,然后由编译器对其进行优化.)

注意:这个问题已被标记为In what scope is a struct member identifier put?的可能副本,但我相信我不会询问有关成员范围的问题,而是关于声明实际创建的内容.然而. Difference between ‘struct’ and ‘typedef struct’ in C++?的答案确实解释了我的问题.

解决方法

根据C标准,结构声明的形式如
struct student_s {
    char* name;
    int age;
    double height;
    struct student_s* next;   
};

是一种类型的声明.引用C11,章节§6.7.2.1

The presence of a struct-declaration-list in a struct-or-union-specifier declares a new type,within a translation unit. The struct-declaration-list is a sequence of declarations for the members of the structure or union. […]

C标准不要求为该类型创建变量(命名或未命名).

在你的第二个片段中,你实际上(尝试)将typedef设置为空.但是,如果您将代码段更改为

typedef struct {
         //.....members
} student_s ;

你将创建一个类型student_s(typedef到一个未命名的结构类型),你可以在以后使用它.

FWIW,我们从不谈论过这里创建的变量.这都是关于类型的.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读