开发者

Enum use in a C program [closed]

It's difficult to tell wha开发者_运维问答t is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

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 #defines, 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜