开发者

value of enum members, when some members have user-defined values

enum ABC{
 A,
 B,
 C=5,
 D,
 E
};

Are D and E guaranteed to be greater than 5 ?

A开发者_C百科re A and B guaranteed to be smaller than 5 (if possible)?

edit: What would happen if i say C=1


It is guaranteed by C++ Standard 7.2/1:

The identifiers in an enumerator-list are declared as constants, and can appear wherever constants are required. An enumerator-definition with = gives the associated enumerator the value indicated by the constant-expression. The constant-expression shall be of integral or enumeration type. If the first enumerator has no initializer, the value of the corresponding constant is zero. An enumerator-definition without an initializer gives the enumerator the value obtained by increasing the value of the previous enumerator by one.


In your situation, yes (see Kirill's answer). However, beware the following situation:

enum ABC
{ 
  A,
  B,
  C = 5,
  D,
  E,
  F = 4,
  G,
  H
};

The compiler will not avoid collisions with previously used values, nor will it try to make each value greater than all previous values. In this case, G will be greater than F, but not C, D, or E.


Yeah it is guaranteed and the value of A and B has to be 0 and 1 respectively.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜