The value of enumeration members when some members have custom values

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

Does D and E mean more than 5?
Are A and B guaranteed less than 5 (if possible)?

edit . What happens if I say C=1

+4
source share
3 answers

This is guaranteed by the C ++ 7.2 / 1 standard:

Identifiers in the enumeration list are declared as constants and can appear where mandatory constants exist. The definition of the enumerator c = assigns to the corresponding enumerator the value specified by the expression constant. The constant expression must be integer or enumerable. If the first enumerator does not have an initializer, the value of the corresponding constant is zero. Defining an enumerator without an initializer gives the enumerator the value obtained by increasing the value of the previous enumerator by one.

+11
source

In your situation, yes (see Cyril's answer). However, beware of 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 โ€‹โ€‹and will not try to make each value larger than all previous values. In this case, G will be greater than F, but not C, D or E.

+2
source

Yes, this is guaranteed, and the values โ€‹โ€‹of A and B should be 0 and 1, respectively.

0
source

Source: https://habr.com/ru/post/1308994/


All Articles