At what exact moment is a local variable allocated storage?

后端 未结 5 798
执笔经年
执笔经年 2020-12-10 15:19

Suppose we have the following:

void print()
{
     int a;  // declaration
     a = 9;
     cout << a << endl;
}

int main ()
{
     print();
}
         


        
5条回答
  •  我在风中等你
    2020-12-10 15:45

    At least as things are typically implemented, it's in between the two. When you call a function, the compiler will generate code for the function call that evaluates the parameters (if any) and puts them in registers or on the stack. Then, when execution reaches the entry for the function, space for local variables will be allocated on the stack, and locals that need initialization will be initialized. At that point, there might be some code to save registers that are used by the function, shuffle values around to get them into the desired registers and such. The code for the body of the function starts to execute after that.

提交回复
热议问题