Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is enum { a } e = 1; valid?

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>
like image 626
pmor Avatar asked Sep 10 '25 20:09

pmor


2 Answers

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.

like image 152
koder Avatar answered Sep 13 '25 09:09

koder


Valid in C

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 [...]


... implementation-defined and possible unspecified/undefined behavior in C++14 and earlier/C++17 and later

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:

  • Is enum E { a } e = E(2); valid?
like image 33
dfrib Avatar answered Sep 13 '25 09:09

dfrib