← The C Language Lesson 65 of 77 · 10 XP

Storage classes: static, extern, auto, register

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

A storage class determines where a variable lives and who can see it.

auto — an ordinary local variable (the word is almost never written). It's created on entering a block and disappears on leaving it.

static on a local variable: it's created once and keeps its value between calls of the function. At the same time, it's visible only inside the function:

int counter(void)
{
    static int calls = 0;    // initialised once
    return ++calls;          // 1, 2, 3…
}

static on a global variable or function: it's visible only in its own .c file. This is a way to hide a module's internal details, a kind of "private" in C.

extern means "this variable is defined in another file": extern int config_level;. That's how global data is shared between files.

register is an outdated hint, "keep this in a processor register". Compilers have long decided that by themselves, and you can't take the address of a register variable.

Task. Rewrite next_id() from the lesson about scope without a global variable, using static inside the function. The program reads n and prints n numbers.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.