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 just released Vidrio, a free app for macOS and Windows to make your screen-sharing awesomely holographic. Vidrio shows your webcam video on your screen, just like a mirror. Then you just share or record your screen with Zoom, QuickTime, or any other app. Vidrio makes your presentations effortlessly engaging, showing your gestures, gazes, and expressions. #1 on Product Hunt. Available for macOS and Windows.

With Vidrio

With generic competitor

More by Jim

Tagged . All content copyright James Fisher 2016. This post is not associated with my employer. Found an error? Edit this page.