These are the notes for C episode 17. Last episode ended with a puzzle: how do you make a function remember how many times it was called, without a global variable? It starts with Ramu's chai stall, whose cup counter keeps printing 1. You find out why (a local variable's lifetime is one call), try a global variable (it remembers, but anyone can change it), and then invent the real fix, a static local variable. On the way you learn the difference between scope and lifetime, why static starts at 0 and is set up only once, what extern promises, how static makes a global private to its file, and why you can't take the address of a register variable. Every example below was compiled with gcc -O2 -Wno-unused-result main.c -o main -lm (gcc 13, the same command as the SyntaxPilot compiler) and run as shown.
The problem: three cups sold, the counter says 1
Ramu wants his program to count every cup of chai. Each cup calls make_chai() once, and inside it we keep a counter:
#include <stdio.h>
void make_chai() {
int count = 0;
count++;
printf("Chai number %d\n", count);
}
int main() {
make_chai();
make_chai();
make_chai();
return 0;
}
Output:
Chai number 1
Chai number 1
Chai number 1
No error and no warning. The program did exactly what we wrote.
Why it happened: lifetime
Real-life example: the classroom whiteboard.
| In a classroom | In C |
|---|---|
| A period starts: the whiteboard is clean | make_chai() is called: a new count is created and set to 0 |
| The teacher writes 1 on it | count++ makes it 1 |
| The bell rings: the board is wiped | The function returns: count is destroyed |
- Every call makes a brand new
count, starts it at 0, adds 1, prints 1, and throws it away. - How long a variable exists in memory is its lifetime. The lifetime of a normal local variable is one call (more exactly, one run of the block it is in).
- This default has a name:
auto(automatic).auto int count = 0;means exactly the same asint count = 0;, which is why nobody writesautoin C.
In C++ (since C++11)
automeans something completely different: "work out the type for me". In C it is only the storage class.
Fix 1: a global variable, and its risk
Real-life example: a board in the corridor, outside every classroom. Nobody wipes it, but anyone walking past can write on it.
A variable declared outside every function is a global variable. It is created when the program starts and lives until the program ends, and every function in the file can use it.
#include <stdio.h>
int count = 0; // global
void make_chai() {
count++;
printf("Chai number %d\n", count);
}
void close_shop() {
count = 0; // oops: meant another counter
}
int main() {
make_chai();
make_chai();
close_shop();
make_chai();
return 0;
}
Output:
Chai number 1
Chai number 2
Chai number 1
The counter remembers now (1, 2), but close_shop(), written by someone else, reset it, and the third cup is "number 1" again. With a global, every function can change it, so when the value is wrong you have to check every function to find who did it. In a program with hundreds of functions, that is painful.
Fix 2: a static local variable
Real-life example: the notebook in the teacher's drawer.
| In a classroom | In C |
|---|---|
| A notebook in the teacher's own drawer, not wiped when the bell rings | static int count lives for the whole program |
| Only this teacher opens the drawer | It can only be used inside make_chai() |
Add one word:
#include <stdio.h>
void make_chai() {
static int count = 0;
count++;
printf("Chai number %d\n", count);
}
int main() {
make_chai();
make_chai();
make_chai();
return 0;
}
Output:
Chai number 1
Chai number 2
Chai number 3
Why isn't it reset to 0 on every call? A static variable is created and initialised once, before the program starts (it is stored with the globals, not on the call's own memory). The line static int count = 0; is not run again on each call.
It is still private
#include <stdio.h>
void make_chai() {
static int count = 0;
count++;
printf("Chai number %d\n", count);
}
void close_shop() {
count = 0;
}
int main() {
make_chai();
return 0;
}
gcc says:
main.c: In function 'close_shop':
main.c:10:5: error: 'count' undeclared (first use in this function)
10 | count = 0;
| ^~~~~
main.c:10:5: note: each undeclared identifier is reported only once for each function it appears in
For close_shop(), count doesn't exist. The bug from the global version can't even compile now. That error is a good thing.
static and auto side by side
#include <stdio.h>
void visit() {
static int a = 0;
int b = 0;
a++;
b++;
printf("static a = %d, auto b = %d\n", a, b);
}
int main() {
visit();
visit();
visit();
return 0;
}
Output:
static a = 1, auto b = 1
static a = 2, auto b = 1
static a = 3, auto b = 1
Same code, one word different, completely different lifetime.
Scope vs lifetime
Two separate questions you can ask about any variable:
- Scope: where in the code can you use its name?
- Lifetime: how long does its box in memory exist?
| Kind of variable | Where declared | Scope | Lifetime | Starts at (if no value given) |
|---|---|---|---|---|
auto local (the default) |
Inside a block | That block only | One run of the block (one call) | Garbage (whatever was in memory) |
static local |
Inside a block, with static |
That block only | The whole program | 0 |
| Global | Outside every function | From its declaration to the end of the file (and other files via extern) |
The whole program | 0 |
static global |
Outside every function, with static |
This file only | The whole program | 0 |
register local |
Inside a block, with register |
That block only | One run of the block | Garbage |
static on a local variable changes the lifetime but not the scope. That is the whole trick.
Block scope
Any pair of curly braces { } is a block, and a name declared inside it can only be used until its closing brace:
#include <stdio.h>
int main() {
int bill = 100;
{
int tip = 10;
bill += tip;
}
printf("Bill %d, tip %d\n", bill, tip);
return 0;
}
gcc says:
main.c: In function 'main':
main.c:9:39: error: 'tip' undeclared (first use in this function)
9 | printf("Bill %d, tip %d\n", bill, tip);
| ^~~
main.c:9:39: note: each undeclared identifier is reported only once for each function it appears in
The same is true for a loop variable: for (int i = 0; ...) makes an i whose scope is only the loop.
Default values, and the "must be constant" rule
#include <stdio.h>
int main() {
auto int cups = 3;
static int days;
printf("cups = %d, days = %d\n", cups, days);
return 0;
}
Output:
cups = 3, days = 0
autois allowed but never needed.staticand global variables start at 0 if you give no value. A normal local with no value holds garbage (whatever bytes were left in that memory), so always initialise locals yourself.
Because a static is set up before main even runs, its starting value must be a constant the compiler knows:
#include <stdio.h>
int main() {
int start = 100;
static int token = start;
printf("%d\n", token);
return 0;
}
gcc says:
main.c: In function 'main':
main.c:5:24: error: initializer element is not constant
5 | static int token = start;
| ^~~~~
Fix: start it with a fixed number (static int token = 100;) and assign other values later with normal statements.
extern: "it exists somewhere"
Real-life example: a small note in a college corridor saying "Fees: see the main noticeboard". The note doesn't hold the fees; it only tells you they exist somewhere. There is exactly one real noticeboard.
| In a college | In C |
|---|---|
| The note "see the main noticeboard" | extern int total;: a declaration, a promise that total exists somewhere |
| The noticeboard itself | int total = 0;: the definition, the line that actually creates the box |
The compiler reads a file from top to bottom. Here total is defined at the very bottom:
#include <stdio.h>
void add(int rs) {
total += rs;
}
int main() {
add(20);
add(30);
printf("Total: Rs %d\n", total);
return 0;
}
int total = 0; // definition: the real box
gcc says:
main.c: In function 'add':
main.c:4:5: error: 'total' undeclared (first use in this function)
4 | total += rs;
| ^~~~~
main.c:4:5: note: each undeclared identifier is reported only once for each function it appears in
main.c: In function 'main':
main.c:10:30: error: 'total' undeclared (first use in this function)
10 | printf("Total: Rs %d\n", total);
| ^~~~~
Add the promise at the top:
#include <stdio.h>
extern int total; // declaration: it exists
void add(int rs) {
total += rs;
}
int main() {
add(20);
add(30);
printf("Total: Rs %d\n", total);
return 0;
}
int total = 0; // definition: the real box
Output:
Total: Rs 50
externdoes not create a variable. It only says "trust me, it's defined somewhere".- There must be exactly one definition. Many places (many files) can have the
externdeclaration. - The connection between the promise and the real box is made by the linker, the last step that joins all the compiled pieces into one program.
Where extern really shines: many files
In one file you could just move the definition to the top. extern matters when a program is split into files (episode 20 builds this properly):
shop.c
#include <stdio.h>
int total = 0;
void report(void);
int main() {
total = 120;
report();
return 0;
}
report.c
#include <stdio.h>
extern int total;
void report(void) {
printf("Report: total is Rs %d\n", total);
}
gcc shop.c report.c -o shop && ./shop prints:
Report: total is Rs 120
static on a global or a function: private to the file
static has a second job. In front of a global variable or a function, it means "only this file can see it". Change shop.c to static int total = 0; and build again:
report.c:(.text+0xa): undefined reference to `total'
collect2: error: ld returned 1 exit status
report.c's promise can no longer be kept, because total is now private to shop.c. This error comes from the linker (ld), not the compiler. Whether a name can be seen from other files is called its linkage:
- External linkage: visible to other files (normal globals and functions).
- Internal linkage: visible only in its own file (
staticglobals andstaticfunctions). - No linkage: local variables (each one is its own).
register
Real-life example: Ramu keeps loose change in his shirt pocket because it's the fastest place to reach. But a pocket has no shelf number.
register asks the compiler to keep a variable in a CPU register, the processor's own tiny, very fast storage. A register is not part of memory, so it has no address:
#include <stdio.h>
int main() {
register int i = 5;
printf("%p\n", (void *)&i);
return 0;
}
gcc says:
main.c: In function 'main':
main.c:5:5: error: address of register variable 'i' requested
5 | printf("%p\n", (void *)&i);
| ^~~~~~
Modern compilers decide which variables go in registers far better than people can, so register is only a hint and is rarely used today. You'll mostly see it in old code. (It was removed from C++17 entirely.)
The four storage classes at a glance
| Keyword | Used on | What it means |
|---|---|---|
auto |
Local variables | The default. Created at the start of the block, destroyed at the end. |
static |
Local variables | Lives for the whole program, initialised once, starts at 0; still only visible in its block. |
static |
Globals and functions | Private to this file (internal linkage). |
extern |
Variables (and functions) | A declaration only: it is defined somewhere else. No new box. |
register |
Local variables | A speed hint: keep it in a CPU register. You can't use & on it. |
A storage class is the part of a declaration that decides a variable's lifetime, scope and linkage: in short, how long it lives and who can see it.
Common mistakes (and the real gcc messages)
| Mistake | What you see | Why | Fix |
|---|---|---|---|
A counter as a normal local: int count = 0; |
No error: prints 1, 1, 1 |
An auto local is reborn on every call |
static int count = 0; |
| A shared counter as a global | No error: another function resets it (1, 2, 1) |
Every function can change a global | Make it a static local, change it only through one function |
Using a static local from another function |
error: 'count' undeclared (first use in this function) |
A static local's scope is still its own block |
Return it from a function, or pass it as an argument |
| Using a block's variable after the block | error: 'tip' undeclared (first use in this function) |
Its scope ended at the } |
Declare it before the block |
static int token = start; |
error: initializer element is not constant |
A static is set up before main runs |
Start from a constant, assign later |
| Using a global before its definition | error: 'total' undeclared (first use in this function) |
The compiler reads top to bottom | extern int total; at the top, or move the definition up |
extern in one file, static definition in another |
undefined reference to 'total' (from ld) |
static makes it private to its file |
Remove static from the definition |
register int i; then &i |
error: address of register variable 'i' requested |
Registers have no memory address | Remove register |
| Reading an uninitialised local | No error, a random number | auto locals start with garbage |
Always give locals a starting value |
Mini project: Ramu's token machine
Every order gets the next token number, and at the end of the day the program prints total sales. It uses all three ideas: a global for the day's total, a static local for the token number, and auto locals for each order.
#include <stdio.h>
int total_rs = 0; // the whole file sees it
int next_token() {
static int token = 100; // remembers, private
token++;
return token;
}
void order(const char *item, int rs) {
int t = next_token(); // auto: fresh each call
total_rs += rs;
printf("Token %d: %-12s Rs %d\n", t, item, rs);
}
int main() {
order("Masala chai", 20);
order("Samosa", 15);
order("Ginger chai", 25);
printf("Day total: Rs %d\n", total_rs);
return 0;
}
Output:
Token 101: Masala chai Rs 20
Token 102: Samosa Rs 15
Token 103: Ginger chai Rs 25
Day total: Rs 60
next_token()is the only code that can change the token number, so nobody can accidentally hand out token 101 twice.%-12sprints the item name left-aligned in 12 characters, so the prices line up.- Try it: add a function
orders_placed()with its ownstaticcounter thatorder()calls, and print how many orders were placed.
Practice
- Write
greet()that prints how many times it has been called. - Call a function 5 times from a loop; inside it, print a
staticand anautovariable that both start at 0 and go up by 1. - Write
next_roll_no()that hands out roll numbers 1, 2, 3 ... - Use a global with
externat the top of the file and the definition at the bottom.
Solutions
Problems 1 to 3 in one program (verified):
#include <stdio.h>
void greet() {
static int calls = 0;
calls++;
printf("Namaste! (greet called %d times)\n", calls);
}
void compare() {
static int s = 0;
int a = 0;
s++;
a++;
printf("s = %d, a = %d\n", s, a);
}
int next_roll_no() {
static int roll = 0;
return ++roll;
}
int main() {
greet();
greet();
greet();
for (int i = 0; i < 5; i++)
compare();
for (int i = 0; i < 3; i++)
printf("Roll no: %d\n", next_roll_no());
return 0;
}
Output:
Namaste! (greet called 1 times)
Namaste! (greet called 2 times)
Namaste! (greet called 3 times)
s = 1, a = 1
s = 2, a = 1
s = 3, a = 1
s = 4, a = 1
s = 5, a = 1
Roll no: 1
Roll no: 2
Roll no: 3
Problem 4 is the extern int total; program in the extern section above (output Total: Rs 50).
Quick quiz
What does this print when main calls f() twice?
void f() {
static int s = 5;
int a = 5;
s++; a++;
printf("%d %d ", s, a);
}
- A.
6 6 6 6 - B.
6 6 7 7 - C.
6 6 7 6 - D.
5 5 6 6
Answer
C: 6 6 7 6. s is static: it is set to 5 once and remembers, so it is 6, then 7. a is auto: it is reborn as 5 on every call, so it is 6 both times. (Verified output: 6 6 7 6.)
Interview questions
- What is a storage class? Name the four storage classes in C.
- What is the difference between scope and lifetime? Give an example where they differ (a
staticlocal). - What is the default storage class of a local variable? Of a global variable?
- Why does a
staticlocal keep its value between calls? Where is it stored? (With the globals, in the program's data area, not on the call stack.) - What is the default value of an uninitialised
staticor global variable? Of an uninitialised local? - What does
staticmean in front of a global variable or a function? (Internal linkage: private to its file.) - What is the difference between a declaration and a definition? Why can
extern int x;appear many times butint x = 0;only once? - Global variable vs
staticlocal variable: when would you use each? - Can you take the address of a
registervariable? Why not? - Is a
staticlocal thread-safe or re-entrant? (No: every call shares the same variable, so two threads or a recursive call can clash.) - What does
automean in C, and how is it different in C++?
Glossary
| Term | Meaning | Example |
|---|---|---|
| Storage class | The part of a declaration that decides a variable's lifetime, scope and linkage | static int count; |
| Local variable | A variable declared inside a function or block | int count = 0; inside make_chai() |
| Global variable | A variable declared outside every function; every function in the file can use it | int total_rs = 0; at the top |
| Block | Code between a pair of curly braces { } |
The body of a function, loop or if |
| Scope | Where in the code a name can be used | tip can only be used inside its block |
| Lifetime | How long a variable's box exists in memory | One call for an auto local; the whole run for a static |
auto |
The default storage class for locals: created at the start of the block, destroyed at the end | auto int cups = 3; (same as int cups = 3;) |
static (local) |
A local that lives for the whole program, is initialised once, and stays private to its block | static int count = 0; |
static (global or function) |
Makes a global or function private to its own file | static int secret; |
extern |
Declares a variable that is defined somewhere else; creates no new box | extern int total; |
register |
A hint to keep a local in a CPU register; its address can't be taken | register int i = 5; |
| CPU register | A tiny, very fast storage slot inside the processor itself | Where loop counters often live |
| Declaration | Tells the compiler a name exists and its type | extern int total; |
| Definition | Actually creates the variable (or function body); exactly one per program | int total = 0; |
| Initialise | Give a variable its first value when it is created | = 0 in static int count = 0; |
| Garbage value | Whatever bytes were left in memory, seen in an uninitialised local | An uninitialised int x; |
| Constant expression | A value the compiler knows without running the program | 100, 60 * 2 |
| Linkage | Whether a name can be seen from other files | External: normal globals; internal: static globals |
Linker (ld) |
The last build step that joins compiled files into one program and connects extern promises to definitions |
undefined reference to 'total' comes from it |
| Call stack | The memory where each function call keeps its auto locals; freed when the call returns |
count in the first version |
Summary
- A normal local variable is
auto: it is created at every call and destroyed at the end, so a counter inside a function forgets. - A global remembers for the whole program, but any function can change it.
- A
staticlocal remembers between calls, is initialised once, starts at 0, and is still private to its function. Its starting value must be a constant. - Scope is where a name can be used; lifetime is how long it exists.
staticon a local changes the lifetime, not the scope. externis a declaration: a promise that a variable is defined somewhere else. There is exactly one definition.staticon a global or a function makes it private to its file (internal linkage).registeris only a speed hint today, and you can't take a register variable's address.- Mini project: a token machine with a
statictoken number, a global day total andautolocals per order.
Next episode: Bitwise operators: &, |, ^, ~, << and >>, packing eight on/off switches into one byte.