What is static in C?

Like void, the keyword static is another of those overloaded keywords. It has different meanings in different syntactic forms.

1: To modify a variable declaration inside a function body, e.g.

int incr(void) {
  static int ctr;
  ctr++;
  return ctr;
}

This example is equivalent to:


int fresh_1;

int incr(void) {
  fresh_1++;
  return fresh_1;
}

… where fresh_1 is a fresh variable, i.e. not used elsewhere in the program.

2: To modify a variable declaration outside a function body, e.g.

static int ctr;
int incr(void) {
  ctr++;
  return ctr;
}

This is also equivalent to

int fresh_1;

int incr(void) {
  fresh_1++;
  return fresh_1;
}

where fresh_1 is a fresh variable, i.e. not used elsewhere in the program (specifically, other translation units).

3: as a modifier to an array length in the type of a function parameter, e.g.:

int foo(int bar[static 10]) {
  return bar[9];
}

Here, static 10 means “bar points to an array of at least length 10”.

A commenter on SO mentions a very useful trick: instead of taking an argument of type struct foo *, a function can instead take an argument of type struct foo [static 1], which makes the stronger statement that foo points to memory of at least size sizeof(struct foo). That is, [struct 1] is a way to annotate an argument as being non-null!

Unfortunately it seems you can’t use this notation in general types. Is it exclusive to function parameters of the form T x[static n]?


I wrote this because I felt like it. This post is my own, and not associated with my employer.

Jim. Public speaking. Friends. Vidrio.