Anthony
Anthony

Reputation: 12387

Compiler Support for Enum Values

Given an enum declared like so:

enum {
    A,
    B,
    C,
    D
};

What is the general compiler support with reference to § 7.2 of the C++11 standard? Specifically, this excerpt from § 7.2.2:

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.

Can I expect the common, modern compilers (GCC, Intel, Clang, recent versions of CL, others), to give the same results, that is, A = 0, B = 1, C = 2, and D = 3?

Upvotes: 1

Views: 137

Answers (2)

Nicol Bolas
Nicol Bolas

Reputation: 473182

The rule you cite is not new in C++11. It's part of C++03, C++98, C11, C99, and C89. This rule existed before these languages were ever standardized. Java and C# both inherited this behavior with their enums.

Yes, compilers support this part of the langauge. Just like they support if, switch, #define, ints and other basic language constructs.

We're not talking about r-value references or lambdas or something. This is core stuff from before many programmers today were even born.

Upvotes: 6

ForEveR
ForEveR

Reputation: 55887

Yes, if compiler supports standard.

enum { a, b, c=0 };
enum { d, e, f=e+2 };

defines a, c, and d to be zero, b and e to be 1, and f to be 3.

Upvotes: 3

Related Questions