Reputation: 109
Structures have logical existence and come into life when a structure variable is defined. I want to know how are enum's stored do they come into life immediately after there declaration. Is it just a logical existence ?
#include<stdio.h>
enum tag{
a,
b};
struct tag1 {
int temp;
}var;
int main(){
int a=9;
printf("%d %d\n",a,b);
printf("%d\n",var.temp);
}
I have heard that enums are not stored in memory so my question is from where does b get its value from.
Upvotes: 1
Views: 1950
Reputation:
A standard enum is usually implemented as an int32, the compiler will handle your enum as a synonym of int32 .Once a list of values is created for a enumeration those values are stored as literals against their display name(access name given at the time of declaration of enum). Hence your enum is at the end an int32 which is hardcoded into the memory similarly like a constant.
Upvotes: 3
Reputation: 222908
Enumeration constants are values. They behave like other integer values, such as 3 or −87. The compiler builds them into the code as it desires: They may be encoded as immediate operands in instructions, loaded from memory the compiler uses to hold constants, or built into expressions that are partly or completely evaluated at compile time.
Values do not have any lifetime in C’s abstract model of computation. Only objects have lifetimes, and values are not objects. (Objects are reserved portions of memory that are used to represent values.)
Upvotes: 1
Reputation: 9521
I'd advice you to take a look at the definition of object N1570 3.15 object:
region of data storage in the execution environment, the contents of which can represent values
and constant 6.4.4 (p2):
Each constant has a type, determined by its form and value, as detailed later
So it is not specified if a constant requires storage in the execution environment and hence may exist only at compile-time.
Since enumeration constant
is a constant
it is not specified for them either. String literal, for instance are place in the .rodata
section and therefore can be read, but modifying it most likely yeilds SEGV
(although it is UB).
To be more specific, let's try to look at the .rodata
section in your example. Here is objdump -dj .rodata bin_name
:
Disassembly of section .rodata:
0000000000000720 <_IO_stdin_used>:
720: 01 00 02 00 25 64 20 25 64 0a 00 25 64 0a 00 ....%d %d..%d..
As you can see it contains the only string literal.
Upvotes: 1
Reputation: 147
b
is substituted with its value (1 in your case) during the compilation. Therefore it will be treated in a same way as a constant and it is not possible to get its address like a variable.
Upvotes: 2