Scope and the Stack
Compound statements introduce a new programming concept called scope to our code. Scope refers to the lifetime and accessibility of variables within your code.
So far, variables have been accessible from where they are declared to the end of the program. This makes sense, as the variables are created within the program’s instructions.
With compound statements, we create blocks of instructions. These have their own start ({
) and end (}
), and the possibility for things to be created and used within the block. This is known as block-level scope.
Block Level Scope
Languages like C# limit the lifetime and access of variables to the block in which they are declared. Let’s work through this with some examples.
Each compound statement creates a new block, beginning at the open brace ({
) and ending at the close brace (}
). Any variable or constant declared within that block will live until the block ends, at which time the variable is destroyed. As a result, these variables are only accessible within that block’s code, including in any new blocks created within that block.
In the above code, the comments and WriteLine
messages indicate which variables are accessible. Notice how name
is accessible throughout the program, from when it is declared in the program’s main block to when the program ends. Within the two additional blocks, new i
variables are created. These are only accessible within the block in which they are declared.
The Stack
The stack is used to store the variables that you create within the blocks in a program.
This is a visual metaphor — like a stack of books. The main program instructions form the base of the stack, then new blocks are added on top of this like a book being added to the pile. Each block adds a marker for the current top of the stack when it is created. Any new variables are then added above that line, within the scope of the current block. At the end of the block, the top of the stack is reset, much like removing a book from the top of the pile. The block’s variables are now gone, and the top of the stack is returned to the previous block.
Let’s look at an example.
Make sure you declare variables within the right block so that they are accessible when you need them.