Storage classes
Storage classes in C: auto, register, static, extern; their scope, storage duration, linkage, defaults, initialization, and typical exam programs.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Storage classes control where a variable or function lives in memory (for how long), who can see it, and how the linker treats it across files. Engineers use them to write efficient, safe, and modular embedded code, multi-file projects, and to avoid bugs from unintended sharing of data.
Key ideas
Definition: Scope — The region of the program text where an identifier is visible and can be used. Types:
- Block scope: inside
{ }of a function or compound statement; starts at the declaration and ends at the closing}. - File scope: at the top level outside any function; starts at the declaration and lasts to the end of the translation unit (source file after preprocessing).
- (For completeness) Function prototype scope: parameter names in a function prototype; only within the prototype.
- (Also) Function scope: labels (identifiers used with
goto) have function scope; they are visible throughout the function in which they appear.
- Block scope: inside
Definition: Storage duration — The time period for which storage (memory) is reserved for an object during program execution.
- Automatic storage duration: storage is allocated at block entry and freed at block exit (typical on the call stack).
- Static storage duration: storage exists for the entire program run, from before
mainbegins till after it ends. Objects with static storage duration are zero-initialized if no initializer is given.
Definition: Linkage — Determines whether the same identifier in different scopes refers to the same entity across translation units.
- External linkage: the identifier refers to the same entity across different files.
- Internal linkage: the identifier refers to the same entity within one translation unit only.
- No linkage: the identifier refers to a unique entity; it cannot be linked to by other declarations.
Exact statements you must remember:
- At block scope, if no storage class is specified for an object, it has automatic storage duration and no linkage by default.
- At file scope, an object declared without
statichas external linkage and static storage duration by default. A function declared withoutstatichas external linkage by default. - A file-scope declaration with
staticgives internal linkage to that identifier while keeping static storage duration. - An identifier declared with
extern(without an initializer) is a declaration that refers to an object defined elsewhere and does not allocate storage. A declaration withexternand an initializer is a definition and allocates storage (file scope). - Objects with static storage duration (file-scope objects; and block-scope objects declared with
static) are zero-initialized if no initializer is provided. Objects with automatic storage duration that are not initialized have indeterminate values. - A
registervariable suggests the compiler place it in a CPU register; its address cannot be taken using&. Modern compilers may ignore the hint, but the restriction on&still applies in standard C.
The four commonly examined specifiers (with effects):
- auto (block scope only): Gives automatic storage duration. Default for block-scope variables; the
autokeyword is rarely written. - register (block scope only): Suggests register storage; automatic duration; no address-of allowed; may improve performance on some systems.
- static:
- At block scope: Turns a local variable into one with static storage duration; it retains value between function calls; scope remains block scope; no linkage.
- At file scope: Gives internal linkage to objects and functions; storage duration is static.
- extern:
- At file or block scope: Declares (refers to) an external object or function defined elsewhere; does not allocate storage unless an initializer is given at file scope.
- auto (block scope only): Gives automatic storage duration. Default for block-scope variables; the
Clarification: typedef — A storage-class specifier that creates a new name (alias) for an existing type. It does not declare any variable storage. Example:
typedef unsigned long u32;. Examiners may ask it under “storage classes” but conceptually it is a type aliasing tool.Initialization rules to state exactly:
- File-scope variables (with or without
static) and block-scopestaticvariables without an explicit initializer are set to 0 (for arithmetic types), a null pointer for pointers (e.g.,NULL), and for aggregates (arrays/structs), each element/member is zero-initialized (arithmetic members to 0; pointer members to the null pointer). - Automatic (non-static) variables without an initializer hold an indeterminate value; using that value before assignment is undefined behavior.
- File-scope variables (with or without
Multi-file behavior to state exactly:
- One and only one definition of a global object with external linkage must appear across the entire program (One Definition Rule in practice for C objects).
- Additional declarations of the same object in other files should use
externand must match type exactly.
Diagram to draw and label (exams often ask memory layout):
- Draw a vertical memory map with four labeled regions from bottom to top (labels on the right): “Code/Text (functions)”, “Global/Static (Data, BSS)”, “Heap (dynamic memory via malloc)”, “Stack (function calls, automatic variables)”.
- Under “Global/Static” write: file-scope variables (
int g;), and block-scopestaticvariables. Under “Stack” write: automatic variables (auto, plain locals) andregistervariables (conceptually). Draw arrows from the keywordsstatic→Global/Static,auto/register→Stack. Add note: string literals have static storage duration.
Relation to other topics: Storage classes interact with “Functions” (static local variables, static functions), “Pointers” (cannot take address of
register), “Dynamic memory allocation” (heap vs static/stack), and “File handling” (global state across modules).
Formulas
For programming topics, remember these syntax patterns and rules:
auto int x;— Block-scope automatic variable. Default at block scope; rarely written.register int i;— Suggest register storage; cannot use&i.static int x;— At file scope: definition with internal linkage. At block scope: local with static storage duration.static void helper(void);— File-scope function with internal linkage (visible only in this file).extern int x;— Declaration referring to anint xdefined in some file (no storage allocated here).extern int x = 10;— At file scope: definition with external linkage; allocates storage and initializes to 10.int x;— At file scope: tentative definition with external linkage (acts as a definition with zero initialization if no other definition with an initializer appears in that translation unit); static storage duration.typedef unsigned int u32;— Type alias; not a variable; no storage allocated.- Default rules to remember:
- Block scope, no storage class → automatic duration, no linkage.
- File scope object, no
static→ external linkage, static duration. - Functions are
externby default unless declaredstaticat file scope.
Worked examples
Example 1: Static local variable vs automatic local variable Program:
#include <stdio.h>
void counter_demo(void) {
static int s = 0; // static storage duration; initialized once to 0
int a = 0; // automatic; re-initialized on every call
s++;
a++;
printf("s = %d, a = %d\n", s, a);
}
int main(void) {
counter_demo();
counter_demo();
counter_demo();
return 0;
}
Sample input: (none) Exact output:
s = 1, a = 1
s = 2, a = 1
s = 3, a = 1
Explanation: s retains its value between calls (static storage duration). a is created fresh on each call (automatic storage duration).
Example 2: Using extern to refer to a global defined later in the same file (single translation unit) Program:
#include <stdio.h>
extern int g; // declaration; refers to a definition elsewhere
void show(void) {
printf("g = %d\n", g);
}
int g = 42; // definition with external linkage; storage allocated here
int main(void) {
show();
g = 100;
show();
return 0;
}
Sample input: (none) Exact output:
g = 42
g = 100
Explanation: The extern int g; is a declaration; the actual storage is allocated at int g = 42;. The definition can appear later in the file; only a declaration is required before use, and the external linkage is resolved at link time.
Example 3: File-scope static gives internal linkage; block-scope static retains value
Model answer (theory with code snippet and explanation):
Question: “Explain the effect of static at file scope and at block scope. Write a short program to illustrate both.”
Model answer:
- At file scope,
staticgives internal linkage. The identifier is visible only within the current source file (translation unit). Storage duration is static. - At block scope,
staticgives static storage duration to a local variable. The variable preserves its value between function calls. Scope remains the block. Program (single file):
#include <stdio.h>
static int file_counter = 0; // internal linkage, static storage duration
static void incr_file_counter(void) { // internal linkage function
file_counter++;
}
void caller(void) {
static int calls = 0; // block-scope static, retains value
calls++;
incr_file_counter();
printf("calls = %d, file_counter = %d\n", calls, file_counter);
}
int main(void) {
caller();
caller();
return 0;
}
Sample input: (none) Exact output:
calls = 1, file_counter = 1
calls = 2, file_counter = 2
Explanation: file_counter and incr_file_counter are not visible from other files (internal linkage). calls keeps its value across calls. In a multi-file project, other files could not access file_counter directly because of static at file scope.
Note: If you try register int r = 5; printf("%p", (void*)&r); it will not compile because you cannot take the address of a register variable. This is a compile-time rule, though compilers may place r in memory anyway.
Common mistakes
- Thinking
staticat block scope makes a variable “private to the function only for this call.” Reality: it persists across calls; design carefully to avoid unwanted state. - Assuming
registeralways puts data in CPU registers and speeds code. Compilers may ignore it; use it only to meet syllabus expectations, not for performance guarantees. - Taking the address of a
registervariable with&. This is not allowed. - Using uninitialized automatic variables, e.g.,
int a; printf("%d", a);. This is undefined behavior becauseahas an indeterminate value. - Confusing scope and linkage:
staticat file scope changes linkage (external→internal) but not scope (still file scope), whilestaticat block scope changes storage duration (automatic→static), not the block scope itself. - Believing
typedefcreates variables. It does not allocate storage; it only creates a new type name. - Forgetting that objects with static storage duration are zero-initialized by default, leading to unnecessary initializations or wrong exam statements.
For your exam
- Short notes:
auto,register,static,extern, andtypedef. For each: where it can appear, what it changes (duration/linkage/scope), default initialization, and one short code snippet. - Programs: Show
staticlocal retaining value;externreferencing a global; compare outputs across calls. Provide complete code and sample output. - Diagram: Memory layout sketch. Label Code/Text, Global/Static (Data, BSS), Heap, Stack; place examples of variables. Mention that static storage duration objects live for the whole program.
- Multi-file explanation: How to share a global variable across files. State: define once (no
extern) in one.c, declare withexternin headers used by others; match types exactly; avoid defining in headers. - Trick questions: Address-of a
registervariable; initialization defaults; whatstaticdoes to a function at file scope (internal linkage); whetherexternallocates storage. - To score full marks: Use precise keywords, show a small correct program, explain output line-by-line, and state rules like “static storage duration objects are zero-initialized if no initializer is provided.”
Quick check
- At block scope, what is the default storage duration and linkage of a variable declared without any storage-class specifier?
- What is the effect of
staticon a file-scope function declaration? - Will
extern int x;allocate storage forx? If not, when is storage allocated?
Answers: 1) Automatic storage duration and no linkage. 2) It gives the function internal linkage (visible only in that translation unit). 3) No; storage is allocated at the single definition (e.g., int x; or extern int x = value;) at file scope.
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?