Scope is where a name can be used. Lifetime is how long the object exists. Linkage is whether the same name in two translation units refers to the same object or function.
| Kind | Visible | Lifetime |
|---|---|---|
| Block (local) | From declaration to end of block | Automatic: until the block ends |
| Function prototype | The parameter list only | — |
| File scope | From declaration to end of the file | Static storage (the whole program) |
Mental model: a local int n; is a new box each time you enter the block. A file-scope int n; is one box for the program (this translation unit’s copy, subject to linkage). A static local is one box that survives across calls.
void f(void) {
int a = 0; /* automatic: 0 every call */
static int b = 0; /* initialized once; keeps value */
a++;
b++;
}
register is a hint from the 1970s. Do not use it. You cannot take & of a register object if the compiler honours it.| Declaration | Linkage | Meaning |
|---|---|---|
int g; at file scope | External | One g for the whole program (tentative definition rules apply) |
static int g; | Internal | This file only |
extern int g; | External | Declaration: the definition is elsewhere |
/* counter.c */
static int calls; /* not exported */
int next_id(void) {
return ++calls;
}
/* other.c cannot see calls */
static on helpers you do not want in the global namespace. That is C’s “private.”extern declarations in a header. Put the one definition in a .c.int g; in two files: often a link error, sometimes a common-symbol merge — do not rely on it. One definition.int x = 1;
{
int x = 2; /* shadows */
use(x); /* 2 */
}
use(x); /* 1 */
C99: declare variables where you need them, not only at the top of the block. Still keep a declaration close to first use.
static on a file-scope helper so it collides with another file’s helper.static on a local is “thread-safe.” It is shared mutable state (Wave B: threads).extern int g = 1; is a definition. extern int g; is not.static file, then extern.x.~ Good luck with your revision! ~