Learn C
#include "functions/scope_lifetime.h"

Scope & Lifetime in C

#concept

Scope is where a name is visible; lifetime is how long its storage lives — related but different ideas beginners fuse at their peril. Block scope covers braces (loop bodies, if branches, bare blocks), function scope covers labels, file scope covers globals, and prototype scope covers parameter names inside declarations.

Automatic locals live from declaration to block exit (and hold garbage unless initialized); statics and globals live for the whole program; malloc'd memory lives until freed regardless of scope. Shadowing (an inner declaration hiding an outer one) compiles fine and confuses humans — -Wshadow flags it.

#how it works
1

Four scopes

Block (braces), function (labels), file (outside all functions), prototype (inside declarations) — each name lives in exactly one.

2

Automatic vs static duration

Locals die at block exit; statics and globals persist from program start — same visibility rules, different lifetimes.

3

Shadowing hides

An inner int x hides the outer x within its block — legal, confusing, and flaggable with -Wshadow.

4

Heap outlives scope

malloc'd memory survives function return (that's the point) — but the pointer itself still obeys scope, so return it or lose it.

#example
#include <stdio.h>
 
int total = 0;
 
void add(int x) {
int bonus = 10;
total = x + bonus;
}
 
int main(void) {
add(5);
printf("%d\n", total);
return 0;
}
Output
15
1total has file scope and static duration — visible to add and main, alive throughout.
2bonus is block-scoped and automatic — born and dead within one add() call.
3add(5) stores 15 in the shared total, which main then prints.
#use cases
Keeping loop counters block-local so they can't leak
Sharing state deliberately via file-scope variables (sparingly)
Catching shadowing bugs with -Wshadow in reviews
Returning heap pointers (not locals' addresses) from functions

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C yourself — building beats watching.