Why in C++ is stack space allocated for local variable declarations never encountered by the thread of execution?

c++, stack, stack-overflow

Solution

1) There's no reason not to. The C++ standard does not promise that variables inside scopes that are not entered during execution will not have space allocated for them.

2) It's faster and simpler. If all the locals get allocated at once, the code to allocate space for locals consists of a one update to the stack pointer at the beginning of the function, and one at the end. If locals within a scope have to be allocated and deallocated at the beginning and end of that scope, you get a lot more stack pointer updates.

Problem

Why in C++ is stack space allocated for local variable declarations never encountered by the thread of execution? Or, if left undefined by the C++ standard, why do certain compilers allocate stack space for local variable declarations never encountered by the thread of execution? Could a compiler only allocate stack space for variable declarations encountered by the thread of execution and still work? To illustrate, calling this function in Debug mode where variable chars cannot be encountered results in a stack overflow: ``` void f() { if (false) { char chars[INT_MAX]; } } ```

Original source