Nearby lessons
110 of 124C - auto Storage Class
auto is the default storage class for local variables — created on the stack when the block is entered, destroyed when it exits. Learn what it means, why nobody writes it, and how C++11 gave the same keyword a completely different job.
auto Is the Default
Every local variable is automatic whether you say so or not. These two declarations are identical:
Automatic Lifetime
Block Scope, Block Lifetime
An automatic variable belongs to the innermost braces around it — not just to the function:
No Automatic Initialisation
Only Valid Inside a Function
auto is meaningless at file scope, where variables have static lifetime by definition:
auto vs static
The contrast is the whole point of the keyword. One resets, one remembers:
auto | static | |
|---|---|---|
| Stored in | Stack | Data segment |
| Created | On every entry | Once, before main |
| Destroyed | On block exit | When the program ends |
| Default value | Garbage | Zero |
| Keeps its value between calls | No | Yes |
| Safe with recursion / threads | Yes — one per call | No — one shared copy |
Why Automatic Variables Make Recursion Work
Each recursive call gets its own stack frame with its own copy of every automatic variable. That is precisely why recursion works at all:
Never Return the Address of One
The variable is gone the instant the function returns, so its address is worthless:
C's auto Is Not C++'s auto
auto x = 5; in C++ code, that is type deduction, not storage.Common Mistakes
- Assuming automatic means initialised — it means automatically allocated, nothing more.
- Reading an uninitialised local — undefined behaviour, even when it seems to print 0.
- Returning the address of a local — the memory is reclaimed immediately.
- Using
autoat file scope — a compile error. - Expecting a local to remember its value — use
staticfor that. - Declaring a huge array as a local — the stack is small; large buffers belong on the heap.
- Reading C++ tutorials for C's
auto— the keyword means something else there.
auto in C. Its value is conceptual: knowing that your locals are automatic explains why they reset every call, why recursion has independent copies, why a 10 MB local array crashes, and why returning &local is a bug.- auto is the default for every local variable — writing it changes nothing.
- Automatic variables live on the stack and die when the block exits.
- They are not zero-initialised; they hold garbage until you assign.
- auto can only be used inside a function, never at file scope.
- In C++11 and later, auto means "deduce the type" — a different keyword entirely.