The Analogy: Which Rooms Can See the Sign, and How Long the Furniture Stays
Two different questions get muddled together constantly, and separating them clears up most C confusion about variables.
Scope is a question about the source code: from which rooms of the building is this name readable? A name declared inside braces is visible only inside those braces.
Lifetime is a question about time: how long does the actual storage exist? A local variable's storage appears when execution enters its block and disappears when execution leaves.
They usually move together, which is why they get conflated — but not always, and the exceptions are where the interesting behaviour lives. A static local has the scope of one block and the lifetime of the entire program. A malloced object has no scope at all, only a lifetime, and it lasts exactly until you free it. And a pointer can easily outlive the thing it points at, which is C's most productive source of bugs.
Syntax or Core Structure
#include <stdio.h>
int global_counter = 0; /* file scope, lives for the whole program */
void tick(void) {
static int calls = 0; /* block scope, but survives between calls */
int local = 0; /* block scope, recreated on every call */
calls++;
local++;
global_counter++;
printf("calls=%d local=%d global=%d\n", calls, local, global_counter);
}
int main(void) {
tick();
tick();
tick();
return 0;
}
Output:
calls=1 local=1 global=1
calls=2 local=1 global=2
calls=3 local=1 global=3
Three variables, three behaviours, one letter of difference. local resets because its storage is created afresh each call. calls climbs because static gives it the program's lifetime while keeping it private to this function. global_counter climbs too, but any function in the file can touch it, which is the whole problem with globals.
Shadowing
An inner declaration hides an outer one of the same name for the rest of that block.
#include <stdio.h>
int value = 10;
int main(void) {
printf("%d\n", value); /* the global */
{
int value = 20; /* shadows it inside these braces */
printf("%d\n", value);
}
printf("%d\n", value); /* the global again, untouched */
return 0;
}
Output:
10
20
10
This compiles without complaint by default. Build with -Wshadow and it becomes a warning, which is what you want — accidental shadowing looks exactly like a failed assignment.
Technical Depth: The Four Storage Durations
Every object in a C program falls into one of these categories, and the category decides both when it exists and what it starts out holding.
| Declaration | Visible from | Storage lasts | Starts as |
|---|---|---|---|
int x; inside a block | that block only | until the block exits | indeterminate (garbage) |
static int x; inside a block | that block only | the whole program | zero |
int x; at file scope | this file, plus any file that declares it extern | the whole program | zero |
static int x; at file scope | this file only | the whole program | zero |
malloc(sizeof x) | wherever you carry the pointer | until free | indeterminate |
The "starts as" column is worth memorising. Anything with static storage is zero-initialised for free, before main runs. Anything automatic or malloced starts as whatever bytes were in that memory. Reading an automatic variable before writing it is undefined behaviour — not "you get a random number", but genuinely unpredictable, including the compiler assuming it cannot happen and optimising accordingly.
The two meanings of static
The keyword is overloaded, and this trips up almost everyone once.
- Inside a function: "give this variable the program's lifetime." Scope is unchanged.
- At file scope: "give this name internal linkage" — that is, hide it from other translation units. Lifetime is unchanged, because file-scope objects already live for the whole program.
So static inside a block is about time, and static outside a block is about visibility. Same word, opposite axes.
Sharing a variable across files
A header must not define a global, only declare it. Define it in exactly one .c file.
/* ---------- counter.h ---------- */
#ifndef COUNTER_H
#define COUNTER_H
extern int total; /* declaration: "this exists somewhere" */
void bump(void);
#endif
/* ---------- counter.c ---------- */
#include "counter.h"
int total = 0; /* the one and only definition */
static int internal_calls = 0; /* private to this file */
void bump(void) { total++; internal_calls++; }
Put int total = 0; in the header instead and every .c that includes it gets its own definition, so the linker reports a duplicate symbol. The error arrives at link time, not compile time, which is why it reads so cryptically.
When a pointer outlives its target
int *broken_counter(void) {
int n = 0;
return &n; /* n's storage dies the instant we return */
}
The pointer is valid for exactly as long as it takes to return it. Dereferencing it afterwards is undefined behaviour; it often appears to work, because nothing has overwritten that stack slot yet, which makes the bug survive testing and surface in production.
Making n static silences the compiler and fixes the lifetime — but now every caller shares one integer, and two threads calling it at once will corrupt each other. That is a real trade, not a free fix.
Real World Example: Three Designs for an ID Generator
Every system needs unique ids — order numbers, request ids, session tokens. The naive version reaches for a global, and the difference between the three designs below is exactly the difference between code you can test and code you cannot.
Design 1, a global. unsigned long next_id = 1; at file scope, incremented by next_request_id(). Any function anywhere can reset it, no test can run twice without leaking state into the next, and two threads will hand out the same id.
Design 2, a static local. Better: the counter is now private to the function, so nothing else can touch it. But there is still exactly one counter in the process. You cannot have two independent id sequences, you cannot reset it for a test, and it is still not thread-safe.
Design 3, caller-owned state. The function holds no state at all. The caller supplies it.
#include <stdio.h>
typedef struct {
unsigned long next_id;
} IdGen;
void idgen_init(IdGen *g, unsigned long start) {
g->next_id = start;
}
unsigned long idgen_next(IdGen *g) {
return g->next_id++; /* returns the old value, then increments */
}
int main(void) {
IdGen orders, sessions;
idgen_init(&orders, 1);
idgen_init(&sessions, 1000);
/* One call per statement. The order in which a function's arguments are
evaluated is unspecified in C, so never put two side-effecting calls
into a single printf and expect a particular order. */
printf("order: %lu\n", idgen_next(&orders));
printf("order: %lu\n", idgen_next(&orders));
printf("session: %lu\n", idgen_next(&sessions));
printf("order: %lu\n", idgen_next(&orders));
printf("session: %lu\n", idgen_next(&sessions));
return 0;
}
Output:
order: 1
order: 2
session: 1000
order: 3
session: 1001
Two independent sequences from one function, because the state lives in the caller's IdGen objects rather than inside idgen_next. A test can create a fresh IdGen, assert on the first three ids, and throw it away with no cleanup. Each thread can own its own generator. And nothing needed static or a global to get there.
The rule this illustrates: a function that owns hidden state is a function you cannot use twice independently. Push state outward to the caller and the function becomes trivially reusable.
Common Mistakes
- Reading a local before writing it.
int total; for (...) total += x[i];starts from garbage. Automatic variables are not zeroed. Always initialise at the point of declaration.
- Returning the address of a local.
return &n;wherenis automatic gives the caller a pointer to storage that no longer exists. It frequently seems to work, which is the worst possible outcome.
- Expecting a
staticlocal to reset. It is initialised once, beforemain, not once per call. A function that "remembers" the previous call across unrelated uses is almost always this.
- Accidental shadowing. Writing
int count = compute();inside a block when an outercountalready exists. The outer one never changes and the code looks correct. Build with-Wshadow.
- Defining a global in a header.
int total = 0;in a.hincluded by three.cfiles is three definitions and a link error. The header getsextern int total;and one.cgets the definition.
- Confusing the two
statics. Addingstaticto a file-scope variable to "make it persist" does nothing for lifetime — it already persisted. What you changed was who can see it.
- Using a loop counter after the loop.
for (int i = 0; ...)scopesito the loop. If you need the final value, declareibefore the loop.
- A
staticlocal in threaded code. Two threads inside the same function share that one variable with no synchronisation, so increments are lost and values are torn. Caller-owned state avoids the problem entirely.
Best Practices
- Declare each variable in the narrowest scope that works, and initialise it in the same statement that declares it.
- Prefer parameters and return values to shared state. If two functions need the same data, pass it.
- Mark every file-scope variable and every helper function that is not in the header as
static. It shrinks the surface area other files can reach.
- Where a global is genuinely required, declare it
externin exactly one header and define it in exactly one.c.
- Compile with
-Wall -Wextra -Wshadow. Uninitialised reads and shadowed names are exactly the class of bug the compiler is good at spotting.
- Reach for a caller-owned state
structbefore astaticlocal. It costs one parameter and buys testability, multiple instances and thread safety.
- Never return a pointer or a reference to an automatic object. Return by value, write into a caller-supplied buffer, or
mallocand document who frees it.
- Give the globals you do keep a distinctive prefix such as
g_or a module name. Making their cost visible at every use site discourages adding more.
Practice Exercises
- Predict, then run. Copy the three-counter program from the top of this lesson, but before compiling it write down on paper what all nine numbers will be. Then run it. For every value you got wrong, say which of the two questions you answered incorrectly: scope or lifetime.
- Catch a shadow. Write a function with an outer
int totaland an inner block that declares its ownint total, adds to it, and returns the outer one. Compile with-Wall(silent) and then with-Wall -Wshadow(a warning). Fix it by renaming, and add-Wshadowto the build command you use from now on.
- Share a counter, then stop sharing it. Build a three-file program:
counter.hdeclaringextern int total;,counter.cdefining it with abump()function, andmain.ccallingbump()five times and printingtotal. Now move the definition into the header, rebuild, and record the exact link error. Finally convert the design sobump()takes aCounter *and no global exists at all.
- Break a lifetime, then fix it three ways. Write a function returning
&nfor a localint n = 42;, and amainthat prints*pafter calling it. Build normally and note whether it appears to work. Rebuild with-fsanitize=address -gand record what the sanitiser reports. Then fix it three separate ways — return by value, write through a caller-suppliedint *out, andmallocthe integer with a matchingfree— and write one sentence on when each is the right choice.