In C, there is no way to get the number of enumeration values in an enum
, nor the maximum or minimum values. Enumerations are just a handy way to define sets of named constant values, but these values are not stored anywhere. sizeof(enum seq)
is the size of the type used by the compiler to represent values the enumerated type, which is implementation specific, but must be able to represent all of the enumeration constants. In your example the compiler seems to use uint32_t
for this type as all constants fit in this type, hence sizeof(enum seq)
evaluates at compile time to 4
.
Note however that the C Standard specifies this:
6.7.2.2 Enumeration specifiers
...
Constraints
The expression that defines the value of an enumeration constant shall be an integer constant expression that has a value representable as an int
.
Semantics
The identifiers in an enumerator list are declared as constants that have type int
...
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. The enumerated type is incomplete until immediately after the }
that terminates the list of enumerator declarations, and complete thereafter.
Therefore the C Standard does not allow UINT_MAX
as an enumerated value1, but most compilers extend the semantics to handle larger types for enumerations in a compiler specific way. If all values fit in type unsigned int
but not int
, the type of the enumeration could be unsigned int
, but the compiler could also use long
or even long long
.
Also note that you should use %zu
for values of type size_t
such as the value of sizeof(...)
, or cast the value to a specific integer type and use the appropriate conversion specification if your library does not support the C99 z
conversion modifier.
#include <stdio.h>
enum seq { VAL1, VAL2 = 1000000000, VAL3 = UINT_MAX };
int main(void) {
printf("%d\n", (int)sizeof(enum seq)); // may print 4
return 0;
}
1) ignoring the unlikely architectures where INT_MAX == UINT_MAX
.