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 16
, it will result in an exception because num2
is accessed outside of its scope - between line 9
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 13
or line 14
, an exception will be thrown.
Global variables can be accessed anywhere in any scope of the program.
Let's compare a global and local variable:
Output:
At line 5
a global variable is defined.
It can be accessed in both printGlobalVar
and main
functions.
The localVar
variable is defined inside the main
function and can only be accessed inside it.
If we uncomment line 11
, an exception will be thrown because a local variable can only be accessed inside the function it's defined in.