Reputation: 1056
This may seem a very basic question but it is related to how compiler works. What is the sequence of memory allocation to local variables of a function.
Suppose I have a function
int a,b;
int c1;
int c,d;
int c2;
cout<<&a<<endl;
cout<<&b<<endl;
cout<<&c<<endl;
cout<<&d<<endl;
cout<<&c1<<endl;
cout<<&c2<<endl;
int f;
cout<<&f<<endl;
Here f gets the lowest memory address (relative wrt other variables) as if the initialisation stack was build like this:
a b c1 c d c2 f
and then memory was allocated
This might happen because there are various phases of compilation and this is one of them.
Which phase does this stack building up correspond to and in which phase is memory actually allocated?
Upvotes: 0
Views: 701
Reputation: 129
It is compiler dependent. It depends on the type of parsing (top down or bottom up & left or right) done by the parser.
Upvotes: 0
Reputation: 41627
The order in the code is not necessarily related to the order in memory at runtime.
To make the results a little more interesting, you can use differently-sized data types.
#include <iostream>
using std::cout;
using std::endl;
int main() {
int i0;
char c0, c1;
int i1;
short s0;
cout << &i0 << endl;
cout << (void *) &c0 << endl;
cout << (void *) &c1 << endl;
cout << &i1 << endl;
cout << &s0 << endl;
return 0;
}
Using g++ 3.4.4 on cygwin, Windows XP, 32bit, with -Os
I got the following result:
0x22cce0
0x22ccdf
0x22ccde
0x22ccd8
0x22cce6
This suggests that the compiler groups the variables by their size, not by their declaration order. But in general you cannot rely on this. For example, changing the level of optimization to -O0
did change the order in my case.
Upvotes: 0
Reputation: 92261
There are no rules for how local variables are stored in memory, or if they are stored - they might live in a register for the entire function.
Some of them may even share the same memory location (provided they have separate lifetime and their addresses are not taken).
Upvotes: 2
Reputation: 170499
There's no guarantee about what locations those variables will occupy - order of definition only influences order of constructors/destructors invokation.
Upvotes: 6