For the code:
void main()
{
enum a{a,b ,MAX};
printf("%d",MAX);
}
Why is the output 2
in this case?
The output is 2 because MAX is 2. The enum is used to create names for constants. In C, if you don't explicitly specify a value for an item in the enum, the value is 0 if it's the first item, or one greater than the previous for subsequent items. So, in this case: a
is 0, b
is 1, and MAX
is 2.
FYI: an enum is like a bunch of #define
s, except the values do not need to be constants. See the entry on enumerations in the GNU C manual, assuming you use GNU C.
In terms of the values assigned to the identifiers, the C99 standard has this to say (section 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.
精彩评论