Scope of an identifier is the part of the program where the identifier may directly be accessible. In C, all identifiers are lexically(or statically) scoped. C scope rules can be covered under the following two categories.
There are basically 4 scope rules:
Let’s discuss each scope rules with examples:
Now various questions may arise with respect to the scope of access of variables:
Q. What if the inner block itself has one variable with the same name?
Ans: If an inner block declares a variable with the same name as the variable declared by the outer block, then the visibility of the outer block variable ends at the point of the declaration by inner block.
Q. What about functions and parameters passed to functions?
Ans: A function itself is a block. Parameters and other local variables of a function follow the same block scope rules.
Q. Can variables of the block be accessed in another subsequent block?
Ans: No, a variable declared in a block can only be accessed inside the block and all inner blocks of this block.
For example, the following program produces a compiler error:
C
int main()
{
{
int x = 10;
}
{
// Error: x is not accessible here
printf("%d", x);
}
return 0;
}
Error:
prog.c: In function 'main':
prog.c:8:15: error: 'x' undeclared (first use in this function)
printf("%d", x); // Error: x is not accessible here
^
prog.c:8:15: note: each undeclared identifier is
reported only once for each function it appears in
Example:
C
// C program to illustrate scope of variables
#include<stdio.h>
int main()
{
// Initialization of local variables
int x = 1, y = 2, z = 3;
printf("x = %d, y = %d, z = %d\n",
x, y, z);
{
// changing the variables x & y
int x = 10;
float y = 20;
printf("x = %d, y = %f, z = %d\n",
x, y, z);
{
// changing z
int z = 100;
printf("x = %d, y = %f, z = %d\n",
x, y, z);
}
}
return 0;
}
Output:
x = 1, y = 2, z = 3
x = 10, y = 20.000000, z = 3
x = 10, y = 20.000000, z = 100
119 docs|30 tests
|
|
Explore Courses for Computer Science Engineering (CSE) exam
|