Athanasios V.
Athanasios V.

Reputation: 319

block local variables in C++

Where are the block local variables stored (stack, heap or somewhere else)?

int foo() {
  int j;  /*local variable*/
  for(...) {
    int i; /* block local variable*/
  }
}

if both j and i are stored in the stack, how do we differentiate them. Namely, how do we separate the for scope from the outer function scope?

Upvotes: 0

Views: 1157

Answers (1)

Marcus Müller
Marcus Müller

Reputation: 36442

"Scope" is a language feature, meaning that a variable is only visible and living inside the boundaries of the surrounding code block (here: surrounding {}).

"Stack" is a computing architecture feature, which allows for functions to be called, operating on their own set of registers, and then, on returning from these functions, restoring the original state of computing as was saved prior to the function call.

Thus, these two concepts are orthogonal to each other. C++ defines, based on scope, which variables are accessible (or reach the end of their lifetime); the compiler adds stack framing as necessary for function calling.

Upvotes: 3

Related Questions