c - C 程序中枚举的使用

标签 c enums

对于代码:

void main()
{
   enum a{a,b ,MAX};
   printf("%d",MAX);
}

为什么输出是2在这种情况下?

最佳答案

输出为 2,因为 MAX 为 2。枚举用于为常量创建名称。在 C 中,如果没有显式指定枚举中的某个项目的值,则如果它是第一项,则该值为 0;对于后续项目,该值为 0。因此,在本例中:a 为 0,b 为 1,MAX 为 2。

仅供引用:枚举就像一堆#define,只不过值不需要是常量。请参阅the entry on enumerations in the GNU C manual ,假设您使用 GNU C。

就分配给标识符的值而言,C99 标准有这样的规定(6.7.2.2/3 节):

The identifiers in an enumerator list are declared as constants that have type int and may appear wherever such are permitted. An enumerator with = defines its enumeration constant as the value of the constant expression. If the first enumerator has no =, the value of its enumeration constant is 0. Each subsequent enumerator with no = defines its enumeration constant as the value of the constant expression obtained by adding 1 to the value of the previous enumeration constant. The use of enumerators with = may produce enumeration constants with values that duplicate other values in the same enumeration.

关于c - C 程序中枚举的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5740042/

相关文章:

c - C 中的多重条件检查

c - 使用 C 进行输入验证

c - c中的开关和大小写如何匹配?

c# - 如何将自定义枚举描述绑定(bind)到 DataGrid

python-3.x - python - 如何允许在没有类名的情况下从外部访问类属性?

java - 重写枚举中的抽象方法时避免代码重复

hibernate - 如何使用字段将属性注释为枚举

c - 在 C 中意外修改的结构中动态分配的数组

java - 如何将枚举与 switch 语句一起使用?

c - 在 C 中传递地址