scope of a variable
scope of a variable
The scope of a variable in C is the block or the region in the program where a
variable is declared, defined, and used. Outside this region, we cannot access the
variable, and it is treated as an undeclared identifier.
Example
C
// C program to illustrate the scope of a variable
#include <stdio.h>
int main()
{
// Scope of this variable is within main() function
// only.
int var = 34;
printf("%d", var);
return 0;
}
Output
Before change within main: 5
After change within main: 10
2. Local Scope in C
The local scope refers to the region inside a block or a function. It is the space
enclosed between the { } braces.
The variables declared within the local scope are called local variables.
Local variables are visible in the block they are declared in and other blocks
nested inside that block.
Local scope is also called Block scope.
Local variables have no linkage.
Example
C
// C program to illustrate the local scope
#include <stdio.h>
// Driver Code
int main()
{
{
int x = 10, y = 20; // The outer block contains // declaration
of x and
// y, so following statement // is valid and prints // 10 and
20
{
printf("x = %d, y = %d\n", x, y);
{
// y is declared again, // so outer block y is // not accessible in
this block
int y = 40; // Changes the outer block // variable x to 11
x++; // Changes this block's // variable y to 41
y++;
printf("x = %d, y = %d\n", x, y);
} // This statement accesses // only outer block's //
variables
printf("x = %d, y = %d\n", x, y);
}
}
return 0;
}
Output
x = 10, y = 20
x = 11, y = 41
x = 11, y = 20