Enum Size * in practice *

For C ++, before 2011, the standard says that enumerations can be of any size, from byte to long. But in practice, most compilers do their ints, 4 bytes.

So, in practice, are some obscurely current compilers not making their ints?

And it seems to me that I need to clarify that I am not doing anything strange, for example, enumerations> 2 ^ 31. Just simple enumerations. And on 32 or 64-bit systems, my software will not work on 16 bits!

+6
source share
3 answers

If enum always int , then the following would be unsafe:

 enum oops { foo = 32767, bar, /*what am I?*/ }; 

This is because int can be like 16 bits (and this is still surprisingly common). On a system with a 32-bit int you can set foo = 2147483647 , and your compiler will certainly not choose int as the base type.

Thus, smart C ++ bots indicate that the base type enum should be able to display the given values, and the compiler can choose the appropriate one. Given that int often regarded as a native type of machine, it is often a smart choice.

If you want to know the base type of enum , then std :: basic_type provides this.

+7
source

Take a look at any modern compiler:

 #include <iostream> #include <limits> enum MySmallSmall { SmallValue = 0, }; enum MyLongLong { LongValue = std::numeric_limits<long long>::max() }; int main() { std::cout << "sizeof MySmallSmall is " << sizeof(MySmallSmall) << std::endl; std::cout << "sizeof MyLongLong is " << sizeof(MyLongLong) << std::endl; return 0; } 

clang and g ++ output:

sizeof MySmallSmall - 4

sizeof MyLongLong is 8

But for MS Visual Studio both results are 4 (I checked it using this site http://rextester.com/l/cpp_online_compiler_visual not sure which version of the compiler is here)

Thus, you cannot rely on sizeof any enumeration.

+7
source

gnu ++, you can test it with

  #include <iostream> enum Tmp : unsigned long long int { foo = 600000000000, bar = 12, }; int main() { Tmp lol; std::cout << sizeof(lol) << " : " << Tmp::foo << " : " << sizeof(Tmp::foo) << std::endl; } 

The answer will be 8

-3
source

All Articles