Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

enums

sizeof

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.

like image 344
user1002288 Avatar asked Nov 13 '11 23:11

user1002288


People also ask

Why is sizeof enum 4?

The size is four bytes because the enum is stored as an int . With only 12 values, you really only need 4 bits, but 32 bit machines process 32 bit quantities more efficiently than smaller quantities.

What is enum data type in C?

Enumeration or Enum in C is a special kind of data type defined by the user. It consists of constant integrals or integers that are given names by a user. The use of enum in C to name the integer values makes the entire program easy to learn, understand, and maintain by the same or even different programmer.


1 Answers

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.

like image 168
Nicol Bolas Avatar answered Oct 02 '22 09:10

Nicol Bolas