Types of Variable Scope
There are 4 types of Variable Scope, let’s
discuss them one by one:
Local scope refers to variables defined in
current function. Always, a function will first look up for a variable name in
its local scope. Only if it does not find it there, the outer scopes are
checked.
Look at this example
On execution of the above code the variable a
displays the value 7, because it is defined and available in the local scope.
A variable which is declared outside of all the
functions in a program is known as global variable. This means, global variable
can be accessed inside or outside of all the functions in a program. Consider
the following example
On execution of the above code the variable a
which is defined inside the function displays the value 7 for the function call
Disp() and then it displays 10, because a is defined in global scope.
All programming languages permit functions to
be nested. A function (method) with in another function is called nested
function. A variable which is declared inside a function which
contains another function definition with in it, the inner function can also
access the variable of the outer function. This scope is called enclosed scope.
When a compiler or interpreter search for a
variable in a program, it first search Local, and then search Enclosing scopes.
Consider the following example
In the above example Disp1() is defined with in
Disp(). The variable ‘a’ defined in Disp() can be even used by Disp1() because
it is also a member of Disp().
Finally, we discuss about the widest scope. The
built-in scope has all the names that are pre-loaded into the program scope
when we start the compiler or interpreter. Any variable or module which is
defined in the library functions of a programming language has Built-in or
module scope. They are loaded as soon as the library files are imported to the
program.
Normally only Functions or modules come along
with the software, as packages.
Therefore they will come under Built in scope.
Related Topics
Privacy Policy, Terms and Conditions, DMCA Policy and Compliant
Copyright © 2018-2023 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.