It is important to note that each block has its own scope. That means a local variable declared in a branch is not available outside that branch. For example, here is a broken program to compute someoneβs pay, possibly including extra pay for overtime (over 40 hours):
Recall that scope is a tool for managing complexity. It allows us to use the same variable name in different parts of a program without worrying about conflicts. We already know that each function has its own scope, but so do different blocks in a function.
If you try running that program, the compiler will tell you that pay is not defined at the end of main. That is because when a variable is declared inside a block, it is scoped only for that block. Either pay gets created in the if and goes out of scope (is no longer available) at the end of the if, or it gets created in the else and is only available there. To fix the program, we need to declare pay before the if/else structure:
Because pay was declared in main, and not in the if/else blocks, it is in scope until the end of main. When we enter a block, like the if or else in this program, all the variables from the outer scope (main here) are still available. Changes we make to those variables will persist when we leave the inner block.
Scope generally matches the conventions for indentation. If you have a block of code that is indented, the variables declared in that block are only available within that block and any blocks inside of it.
It is possible to declare a variable with the same name in an inner block as in an outer block. This is called shadowing. The inner variable will hide the outer variable, but the outer variable is still there. This can be confusing, so it is best to avoid shadowing when possible.