shaik nisar ahmed
shaik nisar ahmed

Reputation: 45

How are 'enum' values stored in C language?

I know 'enum' data type is a user defined data type, and the 'enum' variables are the size of 'int'.

  1. The above 'identifier' is a set of constant values, which have a alias name for the constant values, how are these values stored in the memory? i mean how is 'value1' stored i.e '0', and 'value2' stored i.e '20', and 'value3' stored i.e '7000', and 'value4' stored i.e '1234567' in the memory.
  2. 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

Answers (2)

Lundin
Lundin

Reputation: 213920

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

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

Some programmer dude
Some programmer dude

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

Related Questions