+ 6

C++ - Size of an enum

Is size of an enum always 4?

11th Sep 2019, 12:43 PM
Paolo De Nictolis
Paolo De Nictolis - avatar
2 Respostas
+ 6
The standards doesn't specify the size of an enum. The size of an enum is the size of the underlying integral type that can hold the biggest enumerated value, usually starts from int(4bytes) , if int cannot hold the values the compiler choose a bigger type. For example if you declare .. enum X{hello=12345677764}; The size will be 8. Since c++11 you can declare a fixed underlying integral type. I think char type still takes 4 bytes in most of the cases, 4 bytes are well optimized in most of the architectures.
11th Sep 2019, 1:27 PM
AZTECCO
AZTECCO - avatar
+ 5
No, you can specify the type of an enum ( as long as it's an integral ). Assuming a 64 bit system: enum class A : unsigned long long {}; = 8 bytes enum class A : char {}; = 1 byte enum class A : int {}; = 4 bytes ( default type )
11th Sep 2019, 12:56 PM
Dennis
Dennis - avatar