Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

enums

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

Are D and E guaranteed to be greater than 5 ?
Are A and B guaranteed to be smaller than 5 (if possible)?

edit: What would happen if i say C=1

like image 534
smerlin Avatar asked Dec 12 '22 22:12

smerlin


2 Answers

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.

like image 33
Bill Avatar answered Jan 19 '23 00:01

Bill


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.

like image 117
Kirill V. Lyadvinsky Avatar answered Jan 18 '23 22:01

Kirill V. Lyadvinsky