Sub topic 2
Storage Classes, Scope, and Lifetime
Assume you know basic C syntax, functions, and how to compile a small program. This chapter explains where a name can be used, how long an object exists, and how storage-class specifiers affect both.
Three separate ideas
A scope is the part of the source code where a name is visible. A lifetime, or storage duration, is the time during program execution when an object exists. Linkage determines whether the same name in different scopes refers to the same object.
C commonly uses these scopes:
- Block scope: A name declared inside
{}is visible from its declaration to the end of that block. - Function scope: A label used by
gotois visible throughout its function. - File scope: A name declared outside every function is visible from its declaration to the end of the source file.
- Prototype scope: A parameter name in a function prototype exists only in that prototype.
Storage classes
| Specifier or form | Typical scope | Storage duration | Main effect |
|---|---|---|---|
| `auto` | Block | Automatic | Created when execution enters the block |
| `register` | Block | Automatic | Suggests register storage; the compiler may ignore it |
| `static` local | Block | Static | Retains its value between calls |
| `static` file-level | File | Static | Gives internal linkage to that file |
| `extern` | Block or file | Usually static | Declares an object defined elsewhere |
A local variable without a storage-class specifier is normally automatic. Its value is not preserved after the function returns.
A local static variable has block scope but static storage duration. It is initialized once and remains alive until the program ends.
#include <stdio.h>
int total = 0; // file scope, external linkage
static int hidden = 7; // file scope, internal linkage
void visit(void) {
int temporary = 10; // automatic on each call
static int calls = 0; // initialized once
calls++;
total += temporary;
printf("%d %d %d\n", calls, total, hidden);
}
int main(void) {
visit();
visit();
return 0;
}The output is:
1 10 7
2 20 7temporary is recreated on every call. calls keeps its previous value. hidden can be used only within this source file because it has internal linkage.
Scope, linkage, and lifetime together
extern does not create a separate object when it merely declares one. It tells the compiler that a definition exists elsewhere, often in another source file. A file-level definition without static normally has external linkage and can be referred to with extern.
A declaration such as static int x; at file scope is different from static int x; inside a function. The first restricts linkage. The second preserves a local object's value.
Exercise
Exercise
What does the second call print for static int n = 0; n++; printf("%d\n", n); inside a function?
Show answer
It prints 2 if the function was called once before, because the static local is initialized only once and retains its value.