Scope & Lifetime in C
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.
Four scopes
Block (braces), function (labels), file (outside all functions), prototype (inside declarations) — each name lives in exactly one.
Automatic vs static duration
Locals die at block exit; statics and globals persist from program start — same visibility rules, different lifetimes.
Shadowing hides
An inner int x hides the outer x within its block — legal, confusing, and flaggable with -Wshadow.
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.
#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;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C yourself — building beats watching.