Scope of a variable is its lifetime in the program.
The region of the program in which it can be accessed.
A scope can also be viewed as the space between two curly brackets - { }.
Example:
Output:
In this example the num1
variable can be accessed anywhere in the Main function.
The num2
variable is defined inside the if statement and can be accessed only inside it - between its curly brackets - { }.
If we uncomment line 17
, it will result in an exception because num2
is accessed outside of its scope - between line 11
and line 13
.
Scopes are not limited only to if statements. It's also valid for loops too.
Let's look at the following example:
Output:
In this case, both variables i
and num
can be accessed
inside their scope - the for loop.
If we uncomment line 15
or line 16
, an exception will be thrown.