Reputation: 45
I know 'enum' data type is a user defined data type, and the 'enum' variables are the size of 'int'.
I know that the 'enum_variable' has a size of 32 bits, not mandatory. But the confusion part here is that how can 32 bits [if] collectively store all the 'enum' values?
enum identifier
{
value1 = 0, value2 = 20, value3 = 7000, value4 = 1234567
} enum_variable;
printf("%d\n",sizeof(enum_variable));
Upvotes: 1
Views: 2824
Reputation: 213920
The enumeration constants, such as value1
, are simply numbers. They are not stored in the enum variable itself, but are stored as any other numeric constant: either as part of the machine code itself (segment often called .text
), or in a separate read-only segment (segment often called .rodata
).
Enumeration constants are guaranteed to be of type int
, but that only matters in the expressions where they are used. How they are actually stored in memory is implementation-defined (depends on system, compiler and linker).
The actual variable can have any size, it is implementation-defined. Though the compiler should pick a size that can fit the largest enumeration constant. Again, it is nothing but a simple integer, it can only hold one number.
In general, enums in C are just "syntactic sugar" on top of plain integers.
Upvotes: 1
Reputation: 409196
Enumeration "values" aren't stored at all, as they are compile-time named constants.
The compiler simply exchanges the use of an enumeration symbol, with the value of it.
Also, the type of an enumeration value is of type int
, so the exact size can differ. But because of that, the enumeration values can be any value in the same range as an int
.
For more information see e.g. this enumeration reference.
Upvotes: 11