SPRUIG8J January 2018 – March 2024
In the following declaration,
enum e
is an enumerated type. Each of a
and b
are enumeration
constants.
enum e { a, b=N };
Each enumerated type is assigned an integer type that can hold all of the enumeration constants. This integer type is the "underlying type." The type of each enumeration constant is also an integer type, and in C might not be the same type. Be careful to note the difference between the underlying type of an enumerated type and the type of an enumeration constant.
The size and signedness chosen for the enumerated type and each enumeration constant depend on the values of the enumeration constants and whether you are compiling for C or C++. C++11 allows you to specify a specific type for an enumeration type; if such a type is provided, it will be used and the rest of this section does not apply.
In C++ mode, the compiler allows enumeration constants up to the largest integral type (64 bits). The C standard says that all enumeration constants in strictly conforming C code (C89/C99) must have a value that fits into the type "int;" however, as an extension, you may use enumeration constants larger than "int" even in C mode.
For the enumerated type, the compiler selects first type in the following list that is big enough and of the correct sign to represent all the values of the enumeration constants:
The "long long" type is skipped because it is the same size as "long."
For example, this enumerated type will have "unsigned char" as its underlying type:
enum uc { a, b, c };
But this one will have "signed char" as its underlying type:
enum sc { a, b, c, d = -1 };
And this one will have "signed short" as its underlying type:
enum ss { a, b, c, d = -1, e = UCHAR_MAX };
For C++, the enumeration constants are all of the same type as the enumerated type.
For C, the enumeration constants are assigned types depending on their value. All enumeration constants with values that can fit into "int" are given type "int," even if the underlying type of the enumerated type is smaller than "int." All enumeration constants that do not fit in an "int" are given the same type as the underlying type of the enumerated type. This means that some enumeration constants may have a different size and signedness than the enumeration type.