C 中的默认枚举值对于所有编译器都相同吗?
如下所示声明枚举时,是否所有 C 编译器都将默认值设置为 x=0
、y=1
和 z=2
在 Linux 和 Windows 系统上?
typedef enum {
x,
y,
z
} someName;
When declaring an enum as shown below, do all C compilers set the default values as x=0
, y=1
, and z=2
on both Linux and Windows systems?
typedef enum {
x,
y,
z
} someName;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
是的。除非您在枚举定义中另行指定,否则初始枚举数的值始终为零,并且每个后续枚举数的值都比前一个枚举数大 1。
Yes. Unless you specify otherwise in the definition of the enumeration, the initial enumerator always has the value zero and the value of each subsequent enumerator is one greater than the previous enumerator.
C99 标准
N1265 C99 草案 在 6.7.2.2/3 说“枚举说明符”
因此,以下内容始终适用于一致的实现:
main.c
编译和运行:
在 Ubuntu 16.04、GCC 6.4.0 中测试。
C99 Standard
The N1265 C99 draft says at 6.7.2.2/3 "Enumeration specifiers"
So the following always holds on conforming implementations:
main.c
Compile and run:
Tested in Ubuntu 16.04, GCC 6.4.0.
如果枚举变量的第一个值未初始化,则 C 编译器会自动分配值 0。编译器会不断将前一个枚举变量的值加 1。
例如:
解释:
jan 的值为 0,feb 为 1,mar 为 2。
说明:
jan 的值为 123,feb 为 999,mar 为 1000。
说明:
jan 的值为“a”,feb 为“s”,mar 为“t”。
If the first value of the enum variable is not initialized then the C compiler automatically assigns the value 0.The compiler keeps on increasing the value of preceeding enum variable by 1.
Eg:
Explanation:
Value of jan will be 0,feb will be 1,mar will be 2.
Explanation:
Value of jan will be 123,feb will be 999,mar will be 1000.
Explanation:
Value of jan will be 'a',feb will be 's',mar will be 't'.
是的,任何平台的枚举值默认从 0 到第 n 个元素开始。
Yes,enum value bydefult start from 0 to n'th element to any platform.