C - Scope and Storage Classes
Scope determines where a name is visible. Storage class determines lifetime and linkage.
Learning Objectives
- Differentiate block, file, and global scope.
- Use
static
,extern
, and automatic storage correctly.
Examples
#include <stdio.h>
int file_scope = 1; // external linkage by default
static int internal = 2; // internal linkage (file-only)
void f(void) {
static int counter = 0; // persists across calls
int local = 5; // automatic storage
counter++;
printf("%d %d %d\n", file_scope, internal, counter);
}
int main(void) {
f(); f(); f();
}
Common Pitfalls
- Forgetting
static
when you want to preserve state across calls. - Confusing
static
at file scope (internal linkage) vs inside a function (persistent lifetime).