Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 135 ยท Functions

Scope and Storage Classes

Learn C scope, lifetime and linkage - block and file scope, shadowing, static local and global variables, extern, register, auto and thread_local explained.

Every variable in C has three properties that decide where you can use it and how long it exists. Scope is the part of the source code where its name is visible. Lifetime (the standard calls it storage duration) is how long the variable exists while the program runs. Linkage decides whether the same name in different source files refers to the same thing. Most of the time you don't think about them, because the defaults are sensible. But the moment you want a counter that survives between function calls, a helper that other files can't see, or a variable shared between files, you need the storage-class specifiers: static, extern, auto, register and thread_local.

This lesson explains each property with small experiments, shows the most useful patterns (and the dangerous ones), and clears up the most confusing keyword in C: static, which means two different things depending on where you write it.

Scope: where a name is visible

C has four kinds of scope. The two you use constantly are block scope and file scope.

  • Block scope: a variable declared inside braces { }, including function parameters and variables declared in a for header, is visible from its declaration to the end of that block.
  • File scope: a variable or function declared outside every function is visible from its declaration to the end of the file. These are usually called global variables.
  • Function scope applies only to goto labels, which are visible throughout their function (break, continue and goto).
  • Function prototype scope covers parameter names in a prototype, which end at the closing parenthesis. That's why prototype names don't have to match the definition (Declarations, Prototypes and Headers).

Shadowing

An inner block may declare a name that already exists in an outer scope. Inside the inner block, the new variable shadows (hides) the outer one:

C Nested scopes and shadowing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The output shows 0, 1, 2 and then 1 again: when the inner block ends, its level disappears and main's is visible again. show() always sees the global, because scope is decided by where the code is written, not by who calls it. Legal as it is, shadowing makes code confusing; GCC warns about it with -Wshadow, which many projects enable.

Declare variables in the smallest scope that works, as close as possible to their first use. A variable that exists only inside a loop body can't be misused after the loop.

Lifetime: automatic and static storage

Lifetime is a run-time property, separate from scope. C has four storage durations:

Storage duration Which variables Created Destroyed
Automatic Locals and parameters (the default inside blocks) When the block is entered When the block ends
Static File-scope variables, and locals declared static Before main starts When the program ends
Allocated Memory from malloc/calloc/realloc When you allocate it When you free it
Thread Variables declared thread_local (C11) When a thread starts When it ends

Automatic variables are fresh every time: a local in a function starts over on every call, and its old value is gone. An automatic variable without an initializer contains garbage (an indeterminate value), and reading it is a bug (Variables). Static variables are different in two ways: they keep their value for the whole run, and if you don't initialize them, they start at zero (0, 0.0 or a null pointer).

C Zero-initialized statics

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Don't rely on this for locals: only static storage is zeroed automatically.

static local variables

Put static in front of a local variable and its lifetime becomes the whole program, while its scope stays the block. It's initialized once, before the program starts, and keeps its value between calls. That gives you private memory for a function:

C A function that remembers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The tickets come out as 1001, 1002 and 1003, and remembered counts 1, 2, 3 while automatic is always 1. The line static int last = 1000; is not executed on each call; it's an initialization that happens once. Because of that, the initializer of a static variable must be a constant expression. static int start = compute_start(); fails with initializer element is not constant in C (C++ allows it).

Static locals are handy for counters, caches and one-time setup. They have costs, though:

  • The function now has hidden state, so the same call can give different results, which makes testing harder.
  • They are shared by all threads. Two threads calling next_ticket at the same time can produce duplicate tickets (Multithreading).
  • A function can safely return a pointer to a static local, because it outlives the call, but every call then overwrites the same buffer. Standard functions like strtok, localtime and asctime work this way, which is why they're awkward in larger programs.
C Returning a pointer to a static buffer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The first line prints 1st 2nd 3rd 4th 11th 12th 13th 21st 102nd, as expected. The second line prints first = 2nd, second = 2nd: both pointers point to the same static buffer, and the second call overwrote it. Returning a pointer to an ordinary local array instead would be far worse: it would dangle, and using it would be undefined behavior (Pointers and Functions). The safer design is to let the caller pass in the buffer, as snprintf does.

Linkage: static and extern at file level

A program is often built from several .c files, each compiled separately and then linked (How C Works). Linkage says whether a file-scope name is shared between them:

  • External linkage (the default for functions and global variables): the name refers to the same entity in every file of the program.
  • Internal linkage (static at file scope): the name is private to its file. Another file can use the same name for something else without a clash.
  • No linkage: local variables. Each one is its own thing.

So static means different things in different places:

Where What static changes
On a local variable Lifetime: it lives for the whole program (scope unchanged)
On a global variable or function Linkage: visible only inside this file (lifetime is already the whole program)

Making file-level helpers static is an important habit. It's C's way of saying "private": it keeps the global namespace clean, prevents accidental clashes between files, and lets the compiler optimize better (it knows nobody else can call the function).

extern: declaring without defining

extern declares a variable without creating it. It says: "this variable exists, with this type, and is defined somewhere else, maybe later in this file or in another file." The usual multi-file pattern looks like this:

C
/* config.h */
extern int verbosity;          /* declaration: every includer may use it */

/* config.c */
int verbosity = 1;             /* the one definition */

/* main.c */
#include "config.h"
void report(void) {
    if (verbosity > 0) { /* ... */ }
}

Our editor compiles a single file, but extern works within one file too. Here, main uses a variable whose definition comes later:

C extern and static in one file

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Functions have external linkage by default, so extern in a function prototype is allowed but redundant: extern int add(int, int); and int add(int, int); mean the same. Multi-File Programs and Linkage builds a real multi-file project with headers, extern and static.

Global variables (external linkage, mutable) make programs hard to reason about: any function in any file might change them. Prefer passing values as parameters. When you need shared state, keep it static in one file and provide functions to read and change it.

auto and register

auto is the oldest storage class: it meant "automatic storage", which is already the default for locals, so nobody wrote it. C23 gave it a new job, borrowed from C++: in a declaration with an initializer, auto lets the compiler infer the type:

C C23 auto type inference

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

C23 auto only works for single variables with an initializer, and it needs a C23 compiler (GCC 13+, Clang 18+). In normal C code, write the type; it's rarely long enough to need inference.

register asks the compiler to keep a variable in a CPU register for speed. Modern compilers ignore the hint and allocate registers far better than people can. Its one remaining effect is a restriction: you can't take the address of a register variable, so &x is a compile error (address of register variable 'x' requested). You'll only see it in old code.

thread_local

A thread_local variable has thread storage duration: every thread gets its own copy, created when the thread starts. It was added in C11 as _Thread_local (with a thread_local macro in <threads.h>); C23 made thread_local a keyword:

C
thread_local int error_code = 0;    /* C23 keyword; C11: _Thread_local */

This is how libraries give each thread its own errno without the threads interfering. Multithreading shows it in action.

Putting it together

Declaration Scope Lifetime Linkage
int x; inside a function Block Automatic None
static int x; inside a function Block Static (whole program) None
int x; at file level File Static External
static int x; at file level File Static Internal
extern int x; Where declared (refers to a definition elsewhere) External
int f(void) { ... } File โ€” External
static int f(void) { ... } File โ€” Internal
thread_local int x; at file level File Thread External

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does tick() return on its third call? int tick(void) { static int n = 10; return ++n; }

    The static variable is initialized to 10 once and keeps its value. The calls return 11, 12 and 13.
  2. 2. What does static do to a function defined at file level, like static int helper(void)?

    At file level, static gives internal linkage. Other .c files can't call helper, and they can define their own function with the same name.
  3. 3. What is the value of an int declared at file scope without an initializer?

    Variables with static storage duration, including all file-scope variables, are zero-initialized. Only automatic locals start with garbage.
  4. 4. What does extern int total; do?

    extern declares a variable without defining it. Exactly one file must contain the definition, such as int total = 0;.
  5. 5. A block declares int x = 2; while a global int x = 1; exists. What does printf("%d", x) print inside that block?

    The inner x shadows the global inside the block. Outside the block, x refers to the global again.

Summary

  • Scope is where a name is visible (block or file scope, plus function scope for labels); an inner declaration shadows an outer one.
  • Lifetime is how long a variable exists: automatic (per block entry), static (whole program, zero-initialized by default), allocated (malloc to free) or thread.
  • static on a local keeps its value between calls (initialized once, with a constant); static on a global or function makes it private to the file.
  • Linkage decides whether names are shared across files: external by default for globals and functions, internal with static, none for locals.
  • extern declares a variable defined elsewhere; put extern declarations in headers and the single definition in one .c file.
  • register is obsolete; auto means type inference in C23; thread_local gives each thread its own copy.

Next: Variadic Functions, where you'll write functions like printf that accept any number of arguments.