Skip to content
  • Scope, Linkage & Lifetime · C

Scope, Linkage & Lifetime

LearnViaNotes @learnvianotes· 2 min read

Three independent questions about every identifier: where can the name be used (scope), how long does the object exist (storage duration) and can other files see it (linkage).

Scope — where a name is visible

ScopeBegins / endsExample
BlockDeclaration → closing }Locals, loop variables for (int i…)
FileDeclaration → end of translation unitGlobals, functions
FunctionWhole functionOnly goto labels
Function prototypeEnd of the prototypeint f(int n); — the name n
C
#include <stdio.h>

int x = 1;                           /* file scope */

int main(void) {
    printf("global x = %d\n", x);
    int x = 2;                       /* shadows the global */
    {
        int x = 3;                   /* shadows the outer local */
        printf("inner x = %d\n", x);
    }
    printf("local x = %d\n", x);
    for (int i = 0; i < 1; i++) {
        printf("i = %d\n", i);
    }
    /* i is out of scope here */
    return 0;
}
Output
global x = 1
inner x = 3
local x = 2
i = 0

Storage duration — how long the object lives

DurationObjectsLifetimeWhere
AutomaticLocals, parametersUntil the block exitsStack
StaticGlobals, static locals, string literalsWhole program.data / .bss / .rodata
Allocatedmalloc / calloc / reallocUntil freeHeap
Thread (C11)_Thread_localLifetime of the threadPer-thread storage

Lifetime ends while a pointer lives on

C — rejected: returning the address of a local variable
#include <stdio.h>

int *make_counter(void) {
    int count = 0;
    return &count;           /* address of a local that dies on return */
}

int main(void) {
    int *p = make_counter();
    printf("%d\n", *p);
    return 0;
}
Compiler
main.c:5:13: error: address of stack memory associated with local variable 'count' returned [-Werror,-Wreturn-stack-address]

Fixes: return the value itself, use a static local, let the caller pass a buffer, or allocate with malloc (caller frees).

Linkage — can other files see it?

What is the difference between scope and lifetime?

What is variable shadowing?

Free for students and teachers

Write notes like this one

Cards for every idea, quizzes and flashcards, read aloud — on the web and your phone.

Something wrong with this note? Open it to report