Why is the size of an enum
always 2 or 4 bytes (on a 16- or 32-bit architecture respectively), regardless of the number of enumerators in the type?
Does
The size of an enum
is "an integral type at least large enough to contain any of the values specified in the declaration". Many compilers will just use an int
(possibly unsigned
), but some will use a char
or short
, depending on optimization or other factors. An enum
with less than 128 possible values would fit in a char
(256 for unsigned char
), and you would have to have 32768 (or 65536) values to overflow a short
, and either 2 or 4 billion values to outgrow an int
on most modern systems.
An enum
is essentially just a better way of defining a bunch of different constants. Instead of this:
#define FIRST 0
#define SECOND 1
...
you just:
enum myenum
{ FIRST,
SECOND,
...
};
It helps avoid assigning duplicate values by mistake, and removes your need to even care what the particular values are (unless you really need to).