C Basics · beginner · ~10 min

Scope and lifetime

Understand block, function, and file scope.

Lesson

A variable's scope is where in the code its name is visible; its lifetime is when its storage exists.

  • A variable declared inside {} has block scope and dies when the block ends.
  • A variable declared at file level (outside any function) has file scope. Add static to make it private to the file; without it, the name is exported.
  • A function parameter is a local variable of the function.

Code examples

static int g_count = 0;   // file-private global

int next_id(void) {
    int local_id = ++g_count;  // local, dies at function return
    return local_id;
}

Common mistakes

  • Returning a pointer to a local variable — the storage vanishes at function return; the pointer becomes dangling.
  • Using a global variable as if it were thread-local: globals are shared by every thread.