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 it's curly brackets - { }.
If we uncomment line 15
, it will result in exception because num2
is accessed outside of it's scope - between line 8
and line 12
.
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.
But if we uncomment line 13
or line 14
, an exception will be thrown.