In other words is sizeof(MyEnum) guaranteed to be the same size on all platforms?
You can set an explicit type in C++11 (but not in earlier C++ incarnations):
enum class Drug : char {
Cocaine,
Cannabis,
Crack
};
or
enum Sex : uint32_t {
Male,
Female,
Other
};
Using class
in front of enum
by the way forces users of Drug
to spell it Drug::Cocaine
, for enumerations without the class
in front of their declarations, the spelling is optional (both Sex::Male
and Female
are valid).
Hacks for C++es prior 2011 include the following, which forces a minimal size:
enum Frob {
...
FORCE_DWORD = 0x7fffffff
};
Seen in practice e.g. on ReactOS' DirectX-SDK implementation.
Standards references
7.2 Enumeration Declarations [dcl.enum]
[...]
§6: For an enumeration whose underlying type is not fixed, the underlying type is an integral type that can
represent all the enumerator values defined in the enumeration. If no integral type can represent all the
enumerator values, the enumeration is ill-formed. It is implementation-defined which integral type is used
as the underlying type except that the underlying type shall not be larger than int unless the value of an
enumerator cannot fit in an int or unsigned int. If the enumerator-list is empty, the underlying type is
as if the enumeration had a single enumerator with value 0.