static

suggest change

The static storage class serves different purposes, depending on the location of the declaration in the file:

  1. To give an identifier internal linkage, so other translation units cannot name it. A file-scope static object also has static storage duration.
/* No other translation unit can name this object. */
static int i;

/* Internal linkage. static is not part of the return type. */
static int f(int n);
  1. To save data for use with the next call of a function (scope=block):
#include <stdio.h>

void foo(void)
{
    static int a = 0; /* static storage duration; initialized once, before startup */
    int b = 0;        /* automatic storage duration; created on each call */

    a += 10;
    b += 10;

    printf("static int a = %d, int b = %d\n", a, b);
}

int main(void)
{
    int i;
    for (i = 0; i < 5; i++)
    {
        foo();
    }

    return 0;
}

This code prints:

static int a = 10, int b = 10
static int a = 20, int b = 10
static int a = 30, int b = 10
static int a = 40, int b = 10
static int a = 50, int b = 10

There is one a for the whole program, shared by every caller. Unsynchronized access from more than one thread is a data race, which is undefined behavior. thread_local is the storage class for a distinct object per thread.

  1. Used in function parameters to denote an array is expected to have a constant minimum number of elements and a non-null parameter:
/* a is expected to have at least 512 elements. */
void printInts(int a[static 512])
{
    size_t i;
    for (i = 0; i < 512; ++i)
        printf("%d\n", a[i]);
}

The required number of items (or even a non-null pointer) is not necessarily checked by the compiler, and compilers are not required to notify you in any way if you don’t have enough elements. If a programmer passes fewer than 512 elements or a null pointer, undefined behavior is the result. Since it is impossible to enforce this, extra care must be used when passing a value for that parameter to such a function.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents