Sub topic 2
Storage classes, scope, and lifetime
This chapter assumes you know basic C syntax (declarations, blocks, functions) and the sizes of the basic types. It covers three related questions about every identifier in a C program. Where can its name be used (scope)? How long does its storage exist (lifetime)? Which other files can refer to it (linkage)? GATE questions mix these up on purpose, so keep the three questions separate.
Three separate ideas
- Scope is the region of source text where a name is visible. It is a compile-time property.
- Storage duration (lifetime) is the span of run time during which the object exists and holds its value.
- Linkage decides whether the same name in different files refers to the same object.
A variable can be out of scope yet still alive. A static local is alive for the whole run, but its name is visible only inside its block.
Scope kinds
| Scope | Where declared | Visible |
|---|---|---|
| Block | Inside `{ }`, including function bodies | From the declaration to the end of the block |
| File | Outside every function | From the declaration to the end of the file |
| Function prototype | Parameter names in a prototype | Only inside that prototype |
C also has function scope, but it applies only to goto labels.
An inner declaration hides an outer one with the same name. This is called shadowing.
#include <stdio.h>
int x = 10;
int main(void) {
printf("%d\n", x);
int x = 20;
printf("%d\n", x);
{
int x = 30;
printf("%d\n", x);
}
printf("%d\n", x);
return 0;
}The output is 10, 20, 30, 20, one per line. The first printf runs before the local x is declared, so it sees the global one. When the inner block ends, its x is gone and the middle x is visible again.
The four storage-class specifiers
C has four storage-class specifiers: auto, register, static and extern.
auto
auto is the default for variables declared inside a block. An auto variable is created when control enters its block and destroyed when the block exits. It is normally kept on the call stack. Without an initializer, its value is indeterminate, so reading it is undefined behavior.
register
register is a hint that the variable should be kept in a CPU register. The compiler may ignore the hint. The one rule that is always enforced is that you cannot apply & to a register variable. That is a compile-time error even if the compiler chose to use memory.
static
static has two different effects, depending on where it appears.
- Inside a block: the variable has static storage duration. It is created once, before the program starts, keeps its value between calls, and still has block scope.
- At file scope: the name gets internal linkage. Other files cannot refer to it. The lifetime is unchanged, because file-scope variables already live for the whole run.
#include <stdio.h>
int counter(void) {
static int n = 0;
n++;
return n;
}
int main(void) {
printf("%d ", counter());
printf("%d ", counter());
printf("%d\n", counter());
return 0;
}This prints 1 2 3. The initializer = 0 is not executed on each call. It is applied once, and it must be a constant expression.
extern
extern declares that an object is defined somewhere else. It allocates no storage. File-scope variables have external linkage by default, so two files can share one variable like this.
/* counter.c */
int total = 5;
static int hidden = 7;
int get_hidden(void) { return hidden; }/* main.c */
#include <stdio.h>
extern int total;
int get_hidden(void);
int main(void) {
total++;
printf("%d %d\n", total, get_hidden());
return 0;
}Compile with gcc main.c counter.c. The output is 6 7. Code in main.c cannot name hidden, but it can call a function that reads it. Without static on hidden, the name would have external linkage.
Default initial values
| Kind of object | Storage | Value if not initialized |
|---|---|---|
| Local (`auto`) | Stack | Indeterminate (garbage) |
| Local `static` | Data or BSS segment | Zero |
| File-scope variable | Data or BSS segment | Zero |
| `malloc` memory | Heap | Indeterminate |
| `calloc` memory | Heap | Zero |
Pointers with static storage start as null pointers. The segments are the compiler's and linker's arrangement of the program image: initialized data, zero-filled data (BSS), and so on. The C standard talks about storage duration, not segments, but the segment picture predicts the same answers.
Static locals and recursion
All calls to a function share one copy of its static local. Each call gets its own copy of an auto local. GATE questions use this difference with recursion.
#include <stdio.h>
void g(int n) {
static int depth = 0;
depth++;
if (n > 0) {
g(n - 1);
}
printf("%d ", depth);
}
int main(void) {
g(2);
printf("\n");
return 0;
}The output is 3 3 3. The three calls increment the same depth to 3 before any of them prints. If depth were an ordinary local initialized to 0, each call would print 1, because each frame has its own copy.
Lifetime and dangling pointers
Returning the address of an auto local is a classic trap. The frame is released when the function returns, so the pointer refers to dead storage. Dereferencing it is undefined behavior. The program may print the old value, garbage, or crash. Changing the local to static fixes the problem, because the object then outlives the call.
#include <stdio.h>
int *good(void) {
static int v = 42;
return &v;
}
int main(void) {
printf("%d\n", *good());
return 0;
}This prints 42. The other fix is heap allocation with malloc, which makes the caller responsible for calling free.
Common errors
- Assuming
static int n = 0;inside a function resetsnon every call. It does not. - Treating
staticat file scope as changing the lifetime. It changes linkage only. - Writing
extern int x = 5;at file scope and expecting a plain declaration. With an initializer, it is a definition (compilers usually warn). - Taking
&of aregistervariable. - Expecting uninitialized locals to be zero. Only static-duration objects get that default.
- Using a name after its block ends. This is a compile error. Using the object through a saved pointer is undefined behavior.
Exercises
Exercise
What does this program print? #include <stdio.h> int f(void) { static int s = 1; int a = 1; s += 2; a += 2; return s + a; } int main(void) { f(); printf("%d\n", f()); return 0; }
Show answer
It prints 8. The static variable s keeps its value between calls: it is 1, becomes 3 on the first call, and becomes 5 on the second. The auto variable a is recreated as 1 on each call and becomes 3. The second call returns 5 + 3 = 8.
Exercise
A function declares "int arr[3] = {1, 2, 3};" as an ordinary local and returns arr. The caller then reads the array through the returned pointer. Name the problem, and give two ways to fix it.
Show answer
The array has automatic storage duration, so it is destroyed when the function returns. The returned pointer dangles, and reading through it is undefined behavior. One fix is to declare the array static, so it lives for the whole run. The other is to allocate it with malloc and let the caller call free. A third option is to have the caller pass in an array for the function to fill.