`typedef struct foo {int bar};` 的合法性

2024-03-31

这个问题源于这个问题是一个结构体{...};类型还是未命名变量? https://stackoverflow.com/questions/31877661/is-a-struct-a-type-or-an-unnamed-variable

在这个问题中,OP 询问了

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

我想问一下以上的合法性。编译包含上述内容的代码时是否需要诊断(或者为了更简单,typedef struct foo {int bar;};)?

我的看法是,从语言律师的角度来看,这是合法的,不需要进行诊断。 (旁白:我并不提倡使用这个。它非常值得诊断。如果我错误地编写了上面这样的代码,我非常希望编译器警告我。)


Section 6.7 of the C11 standard dictates the syntax of a declaration: declaration-specifiers init-declarator-listopt ; Note that the init-declarator-list is optional. This might lead one to think that typedef int; is valid. It isn't because the standard also says that

除 static_assert 声明之外的声明应至少声明一个声明符(函数的参数或结构或联合的成员除外)、标签或枚举的成员。

Thus typedef int; and typedef struct {int bar};是非法的,因为它们没有声明声明符、标签或枚举成员。

另一方面,在我看来typedef struct foo {int bar;};是合法的,因为它确实声明了一些东西。特别是,它声明并定义了struct tag foo.

上述推理正确吗?


在您引用的引文中写道,声明除其他事项外还应声明标签。

所以这个声明

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

只是声明struct student_s相当于没有 typedef 说明符的声明

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

它不会在作用域中引入 typedef 名称。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

`typedef struct foo {int bar};` 的合法性 的相关文章

随机推荐