Size of enums in bytes of different compilers [duplicate]
is the size of an enum always the same among different compilers (gcc, visual c and others?). That is, does sizeof() of a specific enum gives the same values with every compiler that follow the C/C++ standards?
No.
In both C and C++ an enum will have a size such that all the values can be represented and be compatible with an integer type. Different compilers may use different algorithm to choose the type (if it is not specified by another standard such a clearly defined ABI). (C++11 allows to specify the underlying type with a new syntax)
"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."
"...An implementation may delay the choice of which integer type until all enumeration constants have been seen."
ISO/IEC 9899:1999 (E) p.105
So we only have upper boundaries for sizeof(enum). On most systems i had sizeof(enum) = 4, but STM compiler made sizeof(enum) = 1/2/4 depending on values written in enum
Edit: it seems that you can set one of your enum's value to max int to ensure that compiler chooses integer as enum size.
精彩评论