1

How enum constants are processed in a C program. I know these constants are not stored in memory. So I wonder how during execution our program refers any enum constant.

enum data 
{
    first_value = 100,
    second_value = 200
};

enum data value;

During execution how "first_value" or "second_value" is referred if they are not in memory?

4
  • The compiler translates them to the values, similar to constants. Commented May 1, 2014 at 4:18
  • 1
    The declaration is enum is wrong there. After first_value = 100 it should be "," not ";". And after second_value = 200 ";" is not required. Commented May 1, 2014 at 4:37
  • 2
    @user3591654 The enum constants works as the defines constants. Compiler just replace all enum constants with its values and then these values can be optimized out or become part of instruction. For example int x = first_value; after compilation become mov dword ptr [esp+1Ch], 64h (this assembly command moves immediate 64h = 100 = first_value to memory address that correspond x variable). As you can see first_value built in the assembly instruction. Note: also your variable value not initialized and can be equal anything. Commented May 1, 2014 at 4:39
  • one advantage to using enums vs define or const is that the compiler can ensure all enums of a type are accounted for in a switch-case statement (in case you add one and forget to add its corresponding case to appropriate functions) and they can be typedefed for other reasons Commented May 1, 2014 at 7:26

1 Answer 1

2

As they cannot change value ever, they are just replaced with their number. In the same way that in the expression

i += 1;

the 1 isn't necessarily stored anywhere (you cannot take its address) the enum values aren't stored anywhere. They might be mixed in with the code, they might be optimised out, they may even be made part of an increment instruction.

Sign up to request clarification or add additional context in comments.

1 Comment

… Or the value might even be placed in an invisible global variable in memory, especially if the number overflows the "immediate value" slot in the instruction. Nothing forbids the compiler from putting enums in memory, it only has the freedom not to do so.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.