The scope of a variable x in the region of the program in which the use of x refers to its declaration. One of the basic reasons for scoping is to keep variables in different parts of the program distinct from one another. Since there are only a small number of short variable names, and programmers share habits about naming of variables (e.g., I for an array index), in any program of moderate size the same variable name will be used in multiple different scopes.
Scoping is generally divided into two classes:
// A C program to demonstrate static scoping.
#include<stdio.h>
int x = 10;
// Called by g()
int f()
{
return x;
}
// g() has its own variable
// named as x and calls f()
int g()
{
int x = 20;
return f();
}
int main()
{
printf("%d", g());
printf("\n");
return 0;
}
Output :
10
To sum up, in static scoping the compiler first searches in the current block, then in global variables, then in successively smaller scopes.
// Since dynamic scoping is very uncommon in
// the familiar languages, we consider the
// following pseudo code as our example. It
// prints 20 in a language that uses dynamic
// scoping.
int x = 10;
// Called by g()
int f()
{
return x;
}
// g() has its own variable
// named as x and calls f()
int g()
{
int x = 20;
return f();
}
main()
{
printf(g());
}
Output in a language that uses Dynamic Scoping :
20
# A perl code to demonstrate dynamic scoping
$x = 10;
sub f
{
return $x;
}
sub g
{
# Since local is used, x uses
# dynamic scoping.
local $x = 20;
return f();
}
print g()."\n";
Output:
20
26 videos|66 docs|30 tests
|
1. What is the difference between static and dynamic scoping in computer science engineering? |
2. How does static scoping work in computer science engineering? |
3. What are the advantages of static scoping in computer science engineering? |
4. How does dynamic scoping work in computer science engineering? |
5. What are the advantages of dynamic scoping in computer science engineering? |
|
Explore Courses for Computer Science Engineering (CSE) exam
|