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.
In your compiler, the size is four bytes because the
enumis stored as anint. With only 12 values, you really only need 4 bits, but 32 bit machines process 32 bit quantities more efficiently than smaller quantities.Without enums, you might be tempted to use raw integers to represent the months. That would work and be efficient, but it would make your code hard to read. With enums, you get efficient storage and readability.
Other compilers could use a byte, int16, uint16 int or uint as long as the variable can contain all the values of the enum.