Is there a way to have a 64 bit enum in C++? Whilst refactoring some code I came across bunch of #defines which would be better as an enum, but being greater than 32 bit causes the compiler to error.
For some reason I thought the following might work:
enum MY_ENUM : unsigned __int64
{
LARGE_VALUE = 0x1000000000000000,
};
For C++ and relaxed C89/C99/C11, the compiler allows enumeration constants up to the largest integral type (64 bits).
On an 8-bit processor, enums can be 16-bits wide. On a 32-bit processor they can be 32-bits wide or more or less. The GCC C compiler will allocate enough memory for an enum to hold any of the values that you have declared. So, if your code only uses values below 256, your enum should be 8 bits wide.
By default, enums are stored at 32-bit numbers compatible with a UInt32 type. Optionally, a different integer storage type can be provided at the end of the declaration, using the of keyword. This can be used to size the enum smaller (Byte or Word) or larger (Int64).
In C language, an enum is guaranteed to be of size of an int . There is a compile time option ( -fshort-enums ) to make it as short (This is mainly useful in case the values are not more than 64K). There is no compile time option to increase its size to 64 bit.
I don't think that's possible with C++98. The underlying representation of enums is up to the compiler. In that case, you are better off using:
const __int64 LARGE_VALUE = 0x1000000000000000L;
As of C++11, it is possible to use enum classes to specify the base type of the enum:
enum class MY_ENUM : unsigned __int64 {
LARGE_VALUE = 0x1000000000000000ULL
};
In addition enum classes introduce a new name scope. So instead of referring to LARGE_VALUE
, you would reference MY_ENUM::LARGE_VALUE
.
C++11 supports this, using this syntax:
enum class Enum2 : __int64 {Val1, Val2, val3};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With