Click here to Skip to main content
15,881,876 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
To withdraw a normal member variable's value from a structure/class the complier reaches the variable by getting the offset of the element from the beginning address of the structure/class and then adding the base address to the offset.

How is a static variable fetched by the compiler?

Sample code:
In both the structures shown below how will the compiler fetch the variables?
C++
struct cde
{
    char c;
    int d;
};

struct xyz
{
    static char x;
    int y;
    static int z;
};

char xyz::x = 'Y';
int xyz::z = 47;

main()
{
 cde C;
 xyz X;

 C.c = 'D';
 C.d = 4;

 X.y = 7;

 printf("%c %d\n",C.c, C.d);
 printf("%c %d %f\n",X.x, X.y, X.z);
}
Posted
Comments
DaveAuld 13-Nov-11 14:39pm    
Homework question?

1 solution

i have hint for you. You stated
Quote:
then adding the base address to the offset.

How does the compiler know where the base address is? The hint is, it knows where the static variables are by the same mechanism.
 
Share this answer
 
Comments
rupeshkp728 13-Nov-11 15:28pm    
Thanks Chuck for the reply.
The normal auto variables are stored on stack and static on data/bss.
So will two copy of struct xyz be created one on stack and other on data/bss having only static members?
Chuck O'Toole 13-Nov-11 15:34pm    
Ignore my previous reply (I deleted it but you probably saw it in e-mail), it was to a different question you asked. Yes, you have some things of type "xyz" in the "global scope" and some in the "local scope". Locals go on the stack, the others are in the main data space.
rupeshkp728 14-Nov-11 3:06am    
Thanks Chuck.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900