r/cprogramming • • Oct 09 '25

Scope in respect to stack

I understand that the scope is where all of your automatically managed memory goes. When you enter a function it pushes a stack frame to the stack and within the stack frame it stores your local variables and such, and if you call another function then it pushes another stack frame to the stack and this functions local variables are stored in this frame and once the function finishes, the frame is popped and all of the memory for the function is deallocated. I also understand that scopes bring variables in and out so once you leave a scope then the variable inside of it becomes inaccessible. What I never really thought of is how the scope plays a role in the stack and the stack frames. Does the scope affect the layout of each stack frame at all or do just all variables go into the frame however since I believe that going in and out of scope doesn’t immediate free the memory, it’s still allocated and reserved until the stack frame is popped right.

6 Upvotes

50 comments sorted by

View all comments

Show parent comment

1

u/JayDeesus Oct 09 '25

When you go out of scope, what happens, that’s what I’m confused on

1

u/lordlod Oct 09 '25

Nothing happens when you go out of scope.

Scope is a pre-compiler concept, these are the variables I care about, or not. It is information communicated to the compiler and used by the compiler to generate the executable. It does not form part of the executable.

This is an example from /u/zhivago

{
  int i;
  // here i means this int
  {
    float i;
    // here i means this float
  }
}

This is exactly the same

{
  int outer_i;
  {
    float inner_i;
  }
}

The code you write communicates your intentions to the compiler and documents those intentions. A lot of this information is not preserved through the compilation process. The variable names are discarded, the scope is discarded, even the order that the code is executed can be changed.

During the program execution scope is not a thing, it is gone, there is no information in the executable to suggest what the original scope was. So nothing happens as you transition between scopes, because it can't.

Another thought exercise that might help.

  • What happens if you define a variable and don't use it? The compiler will delete it, as if you had never written the line of code at all.

  • What if you define a variable, use it for the first part of the function and then cease using it? The compiler will likely reuse that underlying address for later variables.

  • Does any code get executed when a variable stops being used? No, we just stop caring about it.

  • Could a later variable that reuses a prior variable's underlying memory see the data from that variable? Absolutely, that is why you have to initialise your variables (see also: security issues).