scope in C, because scope rules determine where a variable or function can be accessed in a program.
1. What is Scope?
Scope = The region of the program where a variable, function, or identifier is visible and can be used.
In C, scope is determined at compile time (static scoping).
2. Types of Scope in C
2.1 Block Scope (Local Scope)
Example:
#include <stdio.h>
int main() {
int x = 10; // block scope inside main
{
int y = 20; // scope limited to this inner block
printf("%d %d\n", x, y);
}
// printf("%d", y); // ERROR: y not in scope here
}
2.2 Function Scope
-
Labels (used with goto) have function scope.
-
Once declared, a label is visible throughout the function, even before its declaration.
Example:
void test() {
goto label;
label: printf("This works\n");
}
2.3 File Scope (Global Scope)
-
A variable or function declared outside all functions has file scope.
-
It is visible from the point of declaration to the end of the file.
-
If it has external linkage, it can be used in other files via extern.
Example:
int g = 5; // file scope
void func() {
printf("%d\n", g);
}
2.4 Prototype Scope
Example:
void func(int x); // x has prototype scope
3. Storage Class & Scope Relationship
Storage class keywords affect visibility and lifetime:
| Storage Class |
Typical Scope |
Lifetime |
Linkage |
auto |
Block |
Until block ends |
None |
register |
Block |
Until block ends |
None |
static (local) |
Block |
Entire program |
None |
static (global) |
File |
Entire program |
Internal |
extern |
File |
Entire program |
External |
4. Scope vs Lifetime
Scope = Where in the code you can access the variable.
Lifetime = How long the variable exists in memory.
Example:
void func() {
static int counter = 0; // scope = block, lifetime = entire program
counter++;
printf("%d\n", counter);
}
5. Shadowing
If a local variable has the same name as a global one, it hides the global in that scope.
Example:
#include <stdio.h>
int x = 5;
int main() {
int x = 10; // shadows global x
printf("%d\n", x); // prints 10
}
6. Best Practices
-
Prefer the smallest possible scope for variables.
-
Avoid global variables unless necessary.
-
Use static for internal linkage to hide functions/variables from other files.
-
Be cautious with shadowing; it can cause confusion.
Do you want me to make that?