Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory location of enum value in C

Tags:

c

pointers

memory

I think I've read somewhere that it is illegal to take the address of an enum value in C (enum values not being lvalues; however, I can't find any information on this now). Is that correct and, if so, why?


Edit:

Here's an example that clarifies what I mean by "enum value" above. I mean taking the address of first_value below, not taking the address of an actual instance of an enum:

enum myenum
{
    first_value,
    second_value
};
like image 641
olovb Avatar asked Jul 30 '09 13:07

olovb


People also ask

Where is enum stored in memory?

enums are not allocated in memory - they exist only on compilation stage. They only exist to tell compiler what value is Tuesday in ur example.

Where are enum variables stored in C?

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.

How is memory allocated to enum?

On an 8-bit processor, enums can be 16-bits wide. On a 32-bit processor they can be 32-bits wide or more or less. The GCC C compiler will allocate enough memory for an enum to hold any of the values that you have declared. So, if your code only uses values below 256, your enum should be 8 bits wide.

Is enum stored in heap?

Enums are objects in Java, so they are on the heap.


1 Answers

"Enum value" is slightly ambiguous; however, I assume you mean the following:

enum myenum
{
    first_value,
    second_value
};

In this case, it is illegal to take the address of first_value. The reason for this is that first_value does not actually exist in memory anywhere... it is just a constant, effectively another name for the number 0 (of which, of course, you also cannot take the address).

If, on the other hand, you mean whether you can take the address of a variable that is declared as an enum:

enum myenum x;
enum myenum *mypointer=&x;

then that is definitely possible.

like image 200
Martin B Avatar answered Sep 18 '22 17:09

Martin B