C Static keyword

February 1, 2014

In C, static keyword is a "storage class-specifier" (C99, 6.7.1). Dependending on the identifier type (object or function) declaration with file scope, the usage yields a different meaning:

identifier type: function

static void foo();

foo() has internal linkage (C99, 6.2.2). Internal linkage means the identifier is ONLY visible to functions in the SAME compilation unit.

void foo(); // extern void foo();

foo() has external linkage (C99, 6.2.2). External linkage means the identifier is visible to functions in the SAME and OTHER compilation units.

identifier type: object

static object outside a function

#include <stdio.h>

static int x = 2;

int main( void ) {
    printf( "x: %i\n", x);
    x++;
    printf( "x: %i\n", x);
    x++;
    printf( "x: %i\n", x);
}

x has internal linkage (C99, 6.2.2).

x has static storage duration. x object's lifetime is the duration of the entire execution of the program (C99, 6.2.4) and the object x is initialized once prior the execution of the program (C99, 6.2.4).

In our example, it would be:

x: 2 
x: 3
x: 4

static object inside a function

#include <stdio.h>

void foo( void );

void foo( void )
{
    static int x = 10;
    printf( "x: %i\n", x );
    x++;
}

int main( void ) {
    foo();
    foo();
    foo();
}

x has static storage duration. x object's lifetime is the duration of the entire execution of the program (C99, 6.2.4) and the object x is initialized once prior the execution of the program (C99, 6.2.4).

In our example, it would be:

x: 10
x: 11
x: 12

Discussion, links, and tweets

I'm a developer at IO Stark.