The auto keyword
What you'll learn: You will discover the most common yet rarely written keyword in C and how it defines a variable's lifespan within a function.
The invisible default
When you create a variable inside a function—like int score = 0;—you are actually creating an "automatic" variable. In the early days of C, programmers could explicitly write auto int score = 0; to tell the compiler that this variable should be created when the function starts and destroyed when the function ends.
Today, auto is the default for every variable declared inside a set of curly braces {}. Because the compiler assumes you want this behavior, almost no one actually writes the word. It is the "invisible" keyword of the C language.
Think of it like a whiteboard
Imagine a meeting room with a small whiteboard. When a team enters for a meeting, they use the board to jot down temporary notes. As soon as the meeting is over and they leave the room, the board is wiped clean for the next group.
An auto variable works exactly like that whiteboard.
- Entry: When the program enters the function (the "room"), memory is allocated for the variable.
- Usage: The variable holds data while the function is running.
- Exit: When the function reaches its closing brace
}, the variable is "wiped" from memory. It no longer exists.
How it looks in code
Even though you don't need to type it, here is how the keyword looks in practice:
#include <stdio.h>
void calculate() {
// Both of these are "automatic" variables
auto int temporary_value = 10;
int standard_value = 20;
printf("Total: %d", temporary_value + standard_value);
} // At this brace, both variables are automatically destroyed.
If you tried to access temporary_value from outside that function, the compiler would get confused because that variable’s life is tied strictly to the "automatic" scope of the function block.
Why does it exist?
The auto storage class helps your computer manage memory efficiently. Instead of keeping every variable you ever created active for the entire duration of the program, C uses the auto system to clean up after itself. This ensures that your computer's RAM stays fresh and available for other tasks.
Key takeaway
The auto keyword represents the default storage behavior where variables are created at the start of a block and automatically destroyed at the end.