What does this print? void f(void) { static int s = 10; int a = 10; s += 5; a += 5; printf("%d %d ", a, s); } called as f(); f(); f();
A storage class tells the compiler where a variable lives, what it starts with, where its name is visible (scope), how long it exists (lifetime) and whether other files can share it (linkage). C's auto, register, static and extern are tested in almost every paper.
When you declare a variable, the compiler must settle five things: where it is stored, what it holds if you never initialise it, where in the source its name can be used (scope), how long its storage exists at run time (lifetime, or storage duration) and whether other source files can refer to it (linkage). A storage-class specifier — auto, register, static or extern — picks one combination of these answers.
extern int n; is only a declaration, while int n = 5; is a definition.A running C program's memory is normally divided into segments. The text segment holds the machine code (read-only). The initialised data segment holds globals and statics given a non-zero initial value. The BSS segment holds globals and statics without an initialiser and is zero-filled before main starts. The heap serves malloc and grows upward; the stack holds a frame of auto variables for every active function call and grows downward.
#include <stdio.h>
#include <stdlib.h>
int counter = 10; /* initialised data segment */
int total; /* BSS: zero-filled before main starts */
static int hidden; /* BSS, internal linkage (this file only) */
int main(void)
{
int local = 5; /* stack (auto) */
static int calls; /* BSS: static duration, value 0 */
int *heap = malloc(sizeof *heap); /* the pointer itself is on the */
/* stack; the int it points to is */
/* on the heap */
printf("%d %d %d %d %d\n", counter, total, hidden, local, calls); /* 10 0 0 5 0 */
free(heap);
return 0;
}Every variable declared inside a block without a storage-class keyword is auto. Writing auto int x; is legal but redundant, which is why the keyword is almost never seen. An auto variable is created on the stack each time control enters its block and destroyed when control leaves it. It has block scope, automatic lifetime, no linkage, and an indeterminate (garbage) value until you store something in it.
#include <stdio.h>
int main(void)
{
int a = 1; /* auto, visible in the whole of main */
{
int b = 2; /* auto, visible only inside this block */
printf("%d %d\n", a, b);
} /* b is destroyed here */
/* printf("%d", b); error: 'b' undeclared — out of scope */
int c; /* indeterminate: never read it before assigning */
c = a + 1;
printf("%d\n", c);
return 0;
}int main() { { int number = 2; number = 5; } printf("%d", number); } prints neither 2 nor 5 — it is a compile-time error, because number has block scope and does not exist outside the inner braces.Function parameters behave like auto variables of the function's outermost block: each call receives fresh copies of the arguments. Because auto variables vanish when their function returns, never return the address of a local auto variable — the caller would hold a dangling pointer. (C23 gives the keyword auto a second job, type inference as in auto x = 3.5;, but classic syllabi treat auto purely as the default storage class.)
register int i; asks the compiler to keep the variable in a CPU register instead of main memory, because registers are far faster to access. It is only a request: the compiler may ignore it, and modern optimising compilers allocate registers better than programmers do, so they largely disregard the keyword. Apart from the requested location, a register variable behaves exactly like auto — block scope, automatic lifetime, garbage initial value.
&r is a compile-time error even if the compiler actually kept r in memory, so scanf("%d", &r); is illegal for a register variable.int main(void)
{
register int r = 10;
int *p = &r; /* error: address of register variable requested */
return *p;
}auto, register, static and extern. The standard's grammar also files typedef (purely for syntactic convenience) and, from C11, _Thread_local under 'storage-class specifiers'. volatile and const are not storage classes.static does two different jobs depending on where it is written. Inside a function it gives a local variable static storage duration: the variable is created and initialised once, before main begins, and it keeps its value between calls. Its scope remains the block, so no other function can use its name. Without an initialiser it starts at 0.
#include <stdio.h>
void visit(void)
{
static int count = 0; /* initialised once, lives for the whole program */
int temp = 0; /* auto: recreated and reset on every call */
count++;
temp++;
printf("count = %d, temp = %d\n", count, temp);
}
int main(void)
{
visit(); /* count = 1, temp = 1 */
visit(); /* count = 2, temp = 1 */
visit(); /* count = 3, temp = 1 */
return 0;
}At file scope — outside every function — static changes linkage, not lifetime, because globals already live for the whole run. A static global variable or a static function has internal linkage: it is visible only within its own source file (its translation unit), and another file may use the same name for something else without a clash. This is C's tool for information hiding, the nearest thing it has to private.
static int k = 10; is fine, but static int k = rand(); or static int k = n; (n a variable) is a compile error in C — C++ allows both.static int count = 0; is not re-executed on later calls.A variable defined outside all functions is a global (file-scope) variable: static lifetime, default value 0 and external linkage, so any file of the program may use it — provided that file declares it. The keyword extern makes such a declaration: extern int total; says 'an int named total exists somewhere; do not create storage for it here'. When the program is built, the linker connects every use to the single definition.
/* ---------- counter.h : shared declarations ---------- */
extern int total; /* declaration only: no storage */
void add(int n); /* prototype; functions are extern by default */
/* ---------- counter.c : the definitions ---------- */
#include "counter.h"
int total = 0; /* the one definition: storage created here */
static int calls = 0; /* internal linkage: private to counter.c */
void add(int n) { total += n; calls++; }
/* ---------- main.c ---------- */
#include <stdio.h>
#include "counter.h"
int main(void)
{
add(5);
add(7);
printf("%d\n", total); /* 12 */
return 0;
}
/* Adding "extern int calls;" to main.c and using it fails at LINK time:
calls has internal linkage, so no external definition exists. */extern int x; allocates nothing, and at block scope it cannot carry an initialiser. At file scope, extern int x = 5; is treated as a definition (compilers warn).int x; with no initialiser is a tentative definition: if no other definition appears in that file it becomes a definition initialised to 0.void f(void) { extern int late; late++; } followed by int late = 1;.extern before a prototype is optional; static before a function hides it from other files.Each .c file is compiled on its own into an object file (.o); the standard calls each such unit a translation unit. While compiling one file the compiler cannot see any other, so for every name with linkage it writes a symbol into the object file's symbol table, marked either 'defined here' or 'needed from elsewhere' (undefined). The linker then pairs each undefined symbol with exactly one external definition from another object file or library.
| Declaration at file scope | Kind | Linkage | nm letter |
|---|---|---|---|
int a = 5; | definition, initialised data | external | D |
int b; | tentative definition → zero-filled | external | B (C 'common' on older compilers) |
static int c = 5; | definition, initialised data | internal | d |
static int d; | definition, BSS | internal | b |
extern int e; (and e is used) | declaration only | external | U (undefined here) |
void f(void) { … } | function definition | external | T (text) |
static void g(void) { … } | function definition | internal | t |
$ gcc -c sym.c && nm sym.o
0000000000000000 D a
0000000000000000 B b
0000000000000004 d c
0000000000000004 b d
U e
0000000000000000 T f
0000000000000020 t gint x = 0; written in a header that two .c files include.extern int x; (a declaration) in the header, and the single definition int x = 0; in exactly one .c file..h) hold declarations — extern variables, function prototypes, type definitions, macros. Source files (.c) hold definitions, each in exactly one place. Wrap every header in an include guard (#ifndef COUNTER_H … #endif) so that including it twice is harmless.Scopes nest like boxes. A name declared in an inner block hides (shadows) any variable of the same name in an enclosing block or at file scope, from its declaration to the end of the inner block. C has no operator to reach the hidden outer variable (C++ has :: for globals), so a local that shadows a global makes the global invisible by name in that block.
#include <stdio.h>
int x = 10; /* global x */
void show(void)
{
printf("%d\n", x); /* no local x here: uses the global (10) */
}
int main(void)
{
int x = 20; /* hides the global inside main */
{
int x = 30; /* hides main's x inside this block */
printf("%d ", x); /* 30 */
}
printf("%d ", x); /* 20 */
show(); /* 10 */
return 0;
}Scope and lifetime are independent ideas. A static local has block scope (only its own function can name it) but program lifetime; a global has file scope and program lifetime; an auto variable has block scope and block lifetime. That is why a function may return a pointer to its static local and the caller can still use the object, even though the name is invisible outside the function.
| Storage class | Where stored | Default value | Scope | Lifetime | Linkage |
|---|---|---|---|---|---|
auto (default for locals) | stack (memory) | garbage (indeterminate) | block | until the block exits | none |
register | CPU register if granted, else stack | garbage | block | until the block exits | none |
static local | data / BSS segment | 0 | block | whole program; value kept between calls | none |
static global or function | data / BSS segment (a function's code: text) | 0 (variables) | its own source file | whole program | internal |
| global (no keyword) | data / BSS segment | 0 | file; other files via extern | whole program | external |
extern declaration | none — refers to the definition | taken from the definition | where the declaration appears | whole program | external |
const is a type qualifier: it makes an object read-only after initialisation. const int max = 100; must be initialised where it is defined, and max = 200; is a compile error. In C a const variable is not a constant expression, so standard C rejects it as a case label or a file-scope array size (C++ accepts both; some C compilers allow it as an extension). Modifying a const object through a cast pointer is undefined behaviour. With pointers the position matters: const int *p protects the data, int *const p protects the pointer.
volatile warns the compiler that a variable may change in ways the code does not show — a memory-mapped hardware register, a flag set by a signal handler, or memory shared with another thread or device. Every access must then really go to memory: the compiler may not keep the value cached in a register or delete 'redundant' reads in a loop such as while (!ready) { }. const volatile int *status; describes a status register the program may read but not write, while the hardware may change it at any moment.
const int N = 10;#define N 10auto, register, static and extern are storage classes; volatile and const are type qualifiers. A KPSC System Analyst / System Manager paper asked exactly this, with volatile as the answer.Try the problem first, then reveal the working one step at a time.
What does this print? void f(void) { static int s = 10; int a = 10; s += 5; a += 5; printf("%d %d ", a, s); } called as f(); f(); f();
Predict the output: int x = 5; void inc(void) { x++; } int main(void) { int x = 1; inc(); inc(); printf("%d ", x); { extern int x; printf("%d", x); } return 0; }
file1.c contains int count = 3; static int limit = 9; void bump(void) { count++; } and file2.c contains #include <stdio.h>, extern int count; void bump(void); int main(void) { bump(); bump(); printf("%d", count); return 0; }. (a) What is printed when both files are built together? (b) What happens if file2.c also declares extern int limit; and prints it?
For int g; static int s = 4; void f(int p) { int a; static int b; register int r = 1; extern int g; }, give each variable's storage, default value, scope, lifetime and linkage.
Predict the output of int x; static int y; int main(void) { static int z; printf("%d %d %d", x, y, z); return 0; } — and say what changes if z is declared without static.
Trace int sum(int n) { static int s = 0; s += n; return s; } when main runs printf("%d ", sum(1)); printf("%d ", sum(2)); printf("%d", sum(3));
Find and explain the error, if any, in each: (a) register int r; scanf("%d", &r); (b) inside a function: int n = 5; static int m = n; (c) void f(void) { extern int z = 1; } (d) static int helper(void) { return 1; } in a.c, called from b.c (e) at file scope: const int k = 10; int arr[k];
Design: write next_id(), which returns 1, 2, 3, … on successive calls, such that no other function or file can modify the counter. Which storage class did you use and why?
What is printed? int a = 1; void f(void) { a = a * 10; } int main(void) { int a = 2; f(); printf("%d ", a); { static int a = 3; a++; printf("%d ", a); } f(); printf("%d", a); return 0; }
typedef sits among the storage-class specifiers only for grammar convenience.static int c = 0; does not reset c on every call.&r is a compile error even if r ends up in memory.extern int x; allocates nothing, and a missing definition is a linker error, not a compiler error.12 questions. 70 % passes the topic quiz (+30 XP, +20 more for 100 %). Exam scoring: +1 correct, −⅓ wrong.
Modelled on real KPSC questions (reworded) with the same concept and answer; each links to its original paper.
int main(void)
{
{
int val = 2;
val = 5;
}
printf("%d", val);
return 0;
}