The scope of an identifier determines the region of a C program in which that identifier can be accessed. Scope depends on where the identifier is declared.
#include <stdio.h>
int global = 10;
int main()
{
int local = 20;
if (local > 0)
{
int inner = 30;
printf("global = %d\n", global);
printf("local = %d\n", local);
printf("inner = %d\n", inner);
}
printf("local = %d\n", local);
return 0;
}
Example Output #
global = 10
local = 20
inner = 30
local = 20
Explanation #
global is declared outside all functions:
int global = 10;
Its identifier has file scope, so it can be referenced from its declaration to the end of the source file, subject to linkage.
local is declared inside main():
int local = 20;
Its identifier has block scope, so it can be accessed within the block belonging to main() and its nested blocks.
inner is declared inside the if block:
int inner = 30;
Its scope is limited to that block. It cannot be accessed after the closing brace of the if block.
Scope Types #
| Scope | Where the identifier is declared | Scope extends to |
|---|---|---|
| Block scope | Inside a block, such as a function body or {} block |
End of that block |
| Function prototype scope | Inside a function prototype parameter list | End of the function prototype |
| File scope | Outside all functions | End of the source file |
| Function scope | A label declaration | End of the function |
Nested Block Scope #
An inner block can access identifiers declared in an enclosing block:
int a = 10;
{
int b = 20;
printf("%d\n", a);
printf("%d\n", b);
}
Here, b is accessible only inside the inner block, while a is accessible from both the outer and inner blocks.
Scope determines where an identifier is visible. It does not by itself determine how long the associated object exists; storage duration determines the object’s lifetime.