User Tools

Site Tools


programming:c:static

The `static` keyword

In C, the static keyword means a few different things, depending on context.

A variable inside a function

If declared inside a function, the variable will retain its value between calls to that function. For example:

static-variable.c
#include <stdio.h>
 
void foo(void) {
    static int bar = 4;
    printf("%d\n", bar);
    bar++;
}
 
int main(void) {
    printf("bar will start out at 4...\n");
    foo();
    printf("... but now it'll be 5!\n");
    foo();
    return 0;
}

A function inside a source file

A static function is available only inside the translation unit (usually a source file) that it was defined in. This behavior is similar to namespaces or strong scoping in other languages, though it's less powerful. If you try to #include two different files that define the same function (even if static), the compiler will yell at you!

TODO: Make an example.

programming/c/static.txt · Last modified: 2018-08-22 06:08 by zlg