对于代码:
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/