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

user1002288 picture user1002288 · Nov 14, 2011 · Viewed 121.5k times · Source

This is a C++ interview test question not homework.

#include <iostream>
using namespace std;
enum months_t { january, february, march, april, may, june, july, august, september,    
  october, november, december} y2k;

 int main ()
  {
    cout << "sizeof months_t is  " << sizeof(months_t) << endl;
    cout << "sizeof y2k is  " << sizeof(y2k) << endl;
    enum months_t1 { january, february, march, april, may, june, july, august,    
       september, october, november, december} y2k1;
    cout << "sizeof months_t1 is  " << sizeof(months_t1) << endl;
    cout << "sizeof y2k1 is  " << sizeof(y2k1) << endl;
 }

Output:

sizeof months_t is 4
sizeof y2k is 4
sizeof months_t1 is 4
sizeof y2k1 is 4

Why is the size of all of these 4 bytes? Not 12 x 4 = 48 bytes?
I know union elements occupy the same memory location, but this is an enum.

Answer

Nicol Bolas picture Nicol Bolas · Nov 14, 2011

This is a C++ interview test question not homework.

Then your interviewer needs to refresh his recollection with how the C++ standard works. And I quote:

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.

The whole "whose underlying type is not fixed" part is from C++11, but the rest is all standard C++98/03. In short, the sizeof(months_t) is not 4. It is not 2 either. It could be any of those. The standard does not say what size it should be; only that it should be big enough to fit any enumerator.

why the all size is 4 bytes ? not 12 x 4 = 48 bytes ?

Because enums are not variables. The members of an enum are not actual variables; they're just a semi-type-safe form of #define. They're a way of storing a number in a reader-friendly format. The compiler will transform all uses of an enumerator into the actual numerical value.

Enumerators are just another way of talking about a number. january is just shorthand for 0. And how much space does 0 take up? It depends on what you store it in.