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

159 Views Asked by At

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.

2

There are 2 best solutions below

0
On BEST ANSWER

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.

2
On

The compiler does not necessarily parse the code in line by line fashion. During compilation it would have gone through the entire scope/function and determined the amount of memory to allocate on the stack.

That is one of the reason why compilation exists :)