Local variables and block scope
What you'll learn: How to restrict a variable's visibility and lifespan to specific sections of your code using curly braces.
The guest at the party
Imagine you are hosting a house party. A guest walks into the kitchen, uses a specific mug, and leaves that mug on the counter. As long as the party is in the kitchen, everyone knows whose mug that is. However, once the party moves to the backyard and the kitchen door is locked, that guest (and their mug) effectively ceases to exist for the people outside.
In C, a local variable is like that guest. It is created inside a specific "room" of code and is destroyed the moment you leave that room.
Defining the "Room"
In C, rooms are defined by curly braces { }. We call the area between these braces a block. When you declare a variable inside a block, it is "local" to that block.
This leads to two important concepts:
- Scope: Where the variable can be seen. You can only use the variable inside the braces where it was born.
- Lifetime: How long the variable lives. The variable is created when the program reaches its declaration and is instantly erased from memory when the program hits the closing brace
}.
Scope in action
Look at how variables behave when we nest one block inside another:
#include <stdio.h>
int main() {
// This variable is local to the main function
int outerCount = 10;
{
// This is a new block (a sub-room)
int innerCount = 5;
// We can see both here
printf("Outer: %d, Inner: %d\n", outerCount, innerCount);
}
// The innerCount variable is now "dead" and gone.
// The following line would cause an error:
// printf("%d", innerCount);
printf("Outer is still alive: %d\n", outerCount);
return 0;
}
Why does this matter?
Local scope is a safety feature. By keeping variables restricted to small blocks of code, you prevent "name collisions"—where you accidentally change a variable you didn't mean to. It also keeps your computer's memory clean, as C automatically tidies up those variables the moment they are no longer needed.
Key takeaway
A local variable only exists within the curly braces { } where it was defined; once the program passes the closing brace, the variable is deleted.