Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

64 bit enum in C++?

Tags:

c++

enums

64-bit

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,  
};
like image 385
Rob Avatar asked Sep 16 '08 20:09

Rob


People also ask

Can enum be 64 bit?

For C++ and relaxed C89/C99/C11, the compiler allows enumeration constants up to the largest integral type (64 bits).

How many bits is an enum in C?

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.

Are enums 32-bit?

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).

What is the size of enum variable in C?

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.


2 Answers

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.

like image 169
Ferruccio Avatar answered Oct 16 '22 17:10

Ferruccio


C++11 supports this, using this syntax:

enum class Enum2 : __int64 {Val1, Val2, val3};
like image 28
Leon Timmermans Avatar answered Oct 16 '22 19:10

Leon Timmermans