c - C99 语言中具有未命名成员的结构的正确行为是什么?

标签 c visual-c++ gcc struct c99

#include <stdio.h>

struct s {int;};

int main()
{
    printf("Size of 'struct s': %i\n", sizeof(struct s));    
    return 0;
}

Microsoft C 编译器 (cl.exe) 不想编译此代码。

error C2208: 'int' : no members defined using this type

GNU C 编译器 (gcc -std=c99) 编译此代码...

warning: declaration does not declare anything

...并显示结果:

Size of 'struct s': 0

这意味着gcc中的struct s是完整类型,不能重定义。
这是否意味着完整类型的大小可以为零?

此外,如果此声明声明了完整的结构,则消息declaration does not declare anything 是什么意思?

这里是 struct s 在 (gcc -std=c99) 中是一个完整类型的证明。

#include <stdio.h>

struct s {int;};

struct S {
    struct s s; // <=========== No problem to use it
};

int main()
{
    printf("Size of 'struct s': %i\n", sizeof(struct s));

    return 0;
}

最佳答案

根据 C 标准,该行为未定义。

J.2 未定义行为:

The behavior is undefined in the following circumstances:
....
A structure or union is defined without any named members (including those specified indirectly via anonymous structures and unions) (6.7.2.1).

struct s {int;}; 等同于 struct s {};(无成员)并且 GCC 允许将此作为​​ extension .

struct empty {

};

The structure has size zero.

这使得上述程序成为特定于编译器的程序。

关于c - C99 语言中具有未命名成员的结构的正确行为是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28516667/

相关文章:

c++ - 为静态链接构建 gcc

c - GCC 认为 int 指针在 ARM 上未对齐

c++ - 如何在 C++ 中编译位于不同文件中的模板?

linux - 如何在没有互联网连接的情况下在 red hat linux 上安装 gcc 编译器?

c - GCC fatal error : stdio. h: 没有那个文件或目录

c - 解密功能无法按预期工作

c - C 中 scanf 的奇怪行为

c++ - 应用程序和 exe 之间的类大小更改

c++ - 宽字符字符串文字是否以 UTF-16LE 编码?

c - -wrap 选项的 GNU 链接器通配符