Variable Scope
Variable Scope:
Block Variables:
- It’s important to note that variables initialized within a loop are limited to that specific loop. This is called Variable Scope.
- The variables created in the initialize statements of the FOR loop are only available within the loop.
- Trying to use this variable in other parts of your class will lead to an error.
- If you want to create a variable to use elsewhere in your program (such as an accumulator), initialize the variable at the beginning of the class.
- The Scope of a variable defines where a variable can be used.
- The scope of a variable starts when it is declared.
- The scope ends at the end of the block it was declared in.
Block Variables:
- Variables declared within a block, like a loop or an if statement, are Block Variables.
- Block variables are only accessible within the block they are declared.