The identifiers/constants of the enum
have type int
, so it is permissible to assign the values of them to int
variables:
"The identifiers in an enumerator list are declared as constants that have type int
and may appear wherever such are permitted."
C18, §6.7.7.2/3
However, the type of the enumeration can vary per implementation:
"Each enumerated type shall be compatible with char
, a signed integer type, or an unsigned integer type. The choice of type is implementation-defined,131) but shall be capable of representing the values of all the members of the enumeration."
C18, §6.7.7.2/4
So, sticking with enum
type might prevent any kind of type issues when dealing with enum
s beside being more readable.
Another thing is that it is easily possible to assign the constant of another enum
type to day
, if it has type int
.
enum week {Mon, Tue, Wed, Thur, Fri, Sat, Sun};
enum month {Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dez};
int day = Mar;
This compiles with no issues.
A high-leveled compiler can throw a warning for this when using type enum week
for day
instead and adds with this an extra layer of security.
enum week {Mon, Tue, Wed, Thur, Fri, Sat, Sun};
enum month {Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec};
enum week day = Mar;
For example, Clang, 10.0 throws without any additional flag:
"warning: implicit conversion from enumeration type 'enum month' to different enumeration type 'enum week' [-Wenum-conversion]"
GCC, 10.1 needs the -Wall
or -Wenum-conversion
flag to emit the same warning.
Also this post covers a similar concern, but I wouldn't go so far as declaring it as duplicate:
Furthermore, I've found this interesting article: