Reputation: 2661
If I have a c function
int foo(int input)
{
int x = 5;
if( input == 0 ){
int y = 6;
} else {
int z = 7;
}
}
I know that that stack pointer is adjusted when we enter the function, and that makes space for the int x
statement. And I know that y
and z
only exist within the scope of their respective blocks. But when and how is the space for them allocated?
Upvotes: 4
Views: 1381
Reputation: 254481
It's up to the compiler, as long as the space lasts for at least the lifetime of the variable.
Typically, space for all automatic variables in a function is allocated on the stack at the start of the function, and freed when the function returns. Some variables might be placed in registers, if they don't need to have an address. Your variables will probably not exist at all, since they are never used.
Update: As noted in the comments, C (but not yet C++) allows dynamically-sized local arrays. Obviously, space for these can't be allocated until the size is known.
Upvotes: 6
Reputation: 15872
int foo(int input)
{ // BLOCK 1
int x = 5;
if( input == 0 )
{ // BLOCK 2
int y = input * (x + 6);
// other code here
}
else
{ // BLOCK 3
int z = input + x;
// other code here
}
}
The compiler is able to optimize much of this away, but the high level language rules are this:
x
is valid in BLOCK 1
and any sub-blocks (BLOCK 2
and BLOCK 3
).
y
is valid only in BLOCK 2
.
z
is valid only in BLOCK 3
.
The first pass the compiler makes will generally leave these rules in tact. Subsequent passes will typically see that you are not using the variables (or optimize how they are used) and may move them around or not store them in memory at all (e.g. they may simply be put in a register), so trying to equate their scope in the high level language to how it will be optimized in assembly is a fool's errand.
Upvotes: 0