Variable scope
- C course
- Beginner
- Lesson 10/116
- 4 min
Learn the scope of local and global variables.
Variable scope
A variable's scope is the region of code where it is visible. In C, each { } block creates its own scope. A variable declared inside a block is not visible outside:
{
int x = 5;
}
printf("%d", x); // errorThis is called block scope. Variables declared outside are visible inside; inner declarations can shadow outer ones.
Local and global
C has two main kinds of scope:
- Local: declared inside a function or block; visible only there
- Global: declared outside all functions; visible everywhere
A local variable with the same name can shadow a global one. This causes confusion, so avoid reusing the same name.
Practice Use a global variable
Define a global int counter with value 0. Inside main, do counter = counter + 1; and print it with printf using %d.
Starter code
#include <stdio.h>
// define global counter
int main(void) {
// modify and print counter
return 0;
}Sample solution
#include <stdio.h>
int counter = 0;
int main(void) {
counter = counter + 1;
printf("%d", counter);
return 0;
}Expected output
1
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 A variable declared inside a block
- Is visible throughout the program
- Is visible only at the top of the file
- Is visible only inside that block Correct answer
- Is not visible anywhere
Explanation: A variable declared inside a block is visible only inside that block.
2 Inner block opening
if (x > 0) ____
int y = 1;
}
if (x > 0) {
int y = 1;
}
Explanation: { opens a block where you can declare new variables.
3 Match the scope kinds
| Term | Meaning |
|---|---|
Local |
Inside function |
Global |
Outside function |
Block |
Curly braces |
Shadowing |
Inner covers outer |