Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sizeof of an enum on 64 bit machine

Tags:

c

enums

The standard says that an enum type is a integral type between char, signed and unsigned.

But an int into a 32 bit machine should be 4 byte and into a 64 bit machine should be 8 byte. So why my GCC into a 64 bit machine returns 4 as sizeof of this enum?

enum color
{
  RED,
  GREEN,
  BLUE
};

size_t t = sizeof (enum color); // here 4
like image 762
xdevel2000 Avatar asked Sep 30 '22 17:09

xdevel2000


1 Answers

OP: The standard says that an enum type is a integral type between char, signed and unsigned.
A: Close, but not quite. See more @alk

Each enumerated type shall be compatible with char, a signed integer type, or an unsigned integer type. The choice of type is implementation-defined, but shall be capable of representing the values of all the members of the enumeration. C11dr §6.7.2.2 4

OP: But an int on a 32 bit machine should be 4 bytes and on a 64 bit machine should be 8 bytes.
A: No. Although common, a processor's word size and int are usually the same, the C spec does not require that and many implementations do not follow that especially with compilers on 64-bit machines using 32-bit int. Also 8-bit processors (still common in 2014 in the embedded world) would need at least an 16-bit int to be compliant.

OP:why does GCC on a 64 bit machine return 4 as sizeof of this enum?
A: It's the compiler's choice. Likely to match an int size, fairly common with 64-bit compilers.

like image 117
chux - Reinstate Monica Avatar answered Oct 03 '22 02:10

chux - Reinstate Monica