Question

what is the size of an enumerated type?

int main()
{
enum boolean{fl,tr};
int sbool = sizeof(boolean);
boolean a=fl,b=tr;
cout<<"size of Bool Enum: "<<sbool<<endl;
enum months{jan=1,feb,mar,apr,may,jun,jul,aug,sep,oct,nov,dec};
int smon = sizeof(months);
cout<<"size of months enum: "<<smon<<endl;
}

I had written the above code and i got sbool and smon to be 4. Could anyone explain why?

Was it helpful?

Solution

It is implementation-defined which size an enumeration will have. Usually they have size equal to sizeof( int ) because in C enumerators have type int. Though even in C enumerations themselves have implementation defined compatible type. From the C Standard

Each enumerated type shall be compatible with char, a signed integer type, or an unsigned integer type. The choice of type is implementation-defined

In C++ an enumeration has the size of the underlying type. You can make it fixed specifying enum-base or using of a scoped enumeration that has underlying type int if not specified otherwise.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top