A simple question: is enum { a } e = 1;
valid?
In other words: does assigning a value, which isn't present in the set of values of enumeration constants, lead to well-defined behavior?
Demo:
$ gcc t0.c -std=c11 -pedantic -Wall -Wextra -c
<nothing>
$ clang t0.c -std=c11 -pedantic -Wall -Wextra -c
<nothing>
$ icc t0.c -std=c11 -pedantic -Wall -Wextra -c
t0.c(1): warning #188: enumerated type mixed with another type
# note: the same warning for enum { a } e = 0;
$ cl t0.c /std:c11 /Za /c
<nothing>
From the C18 standard in 6.7.2.2:
Each enumerated type shall be compatible with char, a signed integer type, or an unsigned integer type. The choice of type is implementation-defined, but shall be capable of representing the values of all the members of the enumeration.
So yes enum { a } e = 1;
is valid. e
is a 'integer' type so it can take the value 1
. The fact that 1
is not present as an enumeration value is no issue.
The enumeration members only give handy identifiers for some of possible values.
This is valid in C as per e.g. the 202x working draft:
6.7.2.2/4 Each enumerated type shall be compatible with char, a signed integer type, or an unsigned integer type. The choice of type is implementation-defined, but shall be capable of representing the values of all the members of the enumeration
particularly due to the "compatible type" requirement:
6.2.7/1 Two types have compatible type if their types are the same. Additional rules [...]
Whilst out of scope for this Q&A (C tag, not C++), it may be interesting to point out that the same does not hold for C++, where "C style" unscoped enums with no fixed underlying type have subtle differences from C. For details about the C++ case, see the following Q&A:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With