2

Possible Duplicate:
what is the size of an enum type data in C++?

How is enum data type stored internally (I'd imagine as 8/16/32-bit int?) and can it be safely serialized or should I use something like quint8 to store the value? In other words is sizeof(MyEnum) guaranteed to be the same size on all platforms?

Community
  • 1
  • 1
jaho
  • 4,852
  • 6
  • 40
  • 66

4 Answers4

9

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.

Community
  • 1
  • 1
Sebastian Mach
  • 38,570
  • 8
  • 95
  • 130
3

Definitely not. A lot of characteristics of enums are implementation defined. Make sure to pick a real (safe) type and serialize that.

Carl Norum
  • 219,201
  • 40
  • 422
  • 469
1

Size of enum is the same as int, so it's not guaranteed to be of the same length everywhere.

Use one of types defined in stdint.h, like int32_t, int16_t, etc.

piokuc
  • 25,594
  • 11
  • 72
  • 102
0

It will generally be the same as an int, which can be of different sizes. See this answer.

Community
  • 1
  • 1
Prof. Falken
  • 24,226
  • 19
  • 100
  • 173