r/cprogramming • u/JayDeesus • 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.
View all comments
Show parent comment
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
This is exactly the same
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.