Search code examples
c++assemblystack-memory

storage allocation at opening brace of scope in c++?


while reading from BRUCE ECKEL'S THINKING IN C++..i came across the following text

In c++,a variable can be define at any point in a scope,so it might be seem that storage for variable may not be define until its point of definition .It's actually more likely that the compiler will follow in c of allocating all the storage for a scope at the opening brace of scope.

Doubt:I guess its only for storage allocating at stack but my doubt is how compiler get to know that how many objects(or not even a one) is defined inside the main(or other fn) before reaching to its definition in order to allocate storage at the opening brace of scope.


Solution

  • The compiler can analyze the entire function before actually emitting any code. Typically, the compiler will work out, for each braced segment, how much storage is required, and add a single assembly instruction in the function prologue to adjust the stack pointer by that many bytes.

    Actually initializing the variables, however, occurs at the appropriate point in the code.