Suppose we have the following:
void print()
{
int a; // declaration
a = 9;
cout << a << endl;
}
int main ()
{
print();
}
Is the storage for variable a allocated at the moment function print is called in main or is it when execution reaches the declaration inside the function?
This is very much compiler dependent under the covers, but logically the storage is assigned as soon as the variable is declared.
Consider this simplistic C++ example:
When GCC compiles this, the following code is generated (; comments mine):
Everything between _Z6addtwoi and .LCFI2 is boilerplate code used to set up the stack frame (store the previous function’s variables, etc. safely out of the way). That last “subl $16, %esp” is the allocation of the local variable x.
.LCFI2 is the first bit of actual executing code that you’ve typed. “movl $2, -4(%ebp)” is putting the value 2 into the variable. (Initialization, in other words.) Now your space is allocated AND initialized. After that it loads the value into register EDX and follows that by moving your parameter, found in “8(%ebp)”, into another register EAX. It then adds the two together, leaving the result in EAX. This is now the end of any code you’ve actually typed. The rest is again just boilerplate. Since GCC mandates that integers are returned in EAX, no work has to be done for the return value. The “leave” instruction tears down the stack frame and the “ret” instruction returns control back to the caller.
TL;DR summary: you can think of your space as having been allocated with the very first line of executable code in your block (paired {}).
I thought I’d clean this up a bit with explanatory comments seeing as this is the selected answer.