Why and when to use static structures in C programming?

The static keyword in C has several effects, depending on the context it’s applied to.

  • when applied to a variable declared inside a function, the value of that variable will be preserved between function calls.
  • when applied to a variable declared outside a function, or to a function, the visibility of that variable or function is limited to the “translation unit” it’s declared in – ie the file itself. For variables this boils down to a kind of “locally visible global variable”.

Both usages are pretty common in relatively low-level code like drivers.

The former, and the latter when applied to variables, allow functions to retain a notion of state between calls, which can be very useful, but this can also cause all kinds of nasty problems when the code is being used in any context where it is being used concurrently, either by multiple threads or by multiple callers. If you cannot guarantee that the code will strictly be called in sequence by one “user”, you can pass a kind of “context” structure that’s being maintained by the caller on each call.

The latter, applied to functions, allows a programmer to make the function invisible from outside of the module, and it MAY be somewhat faster with some compilers for certain architectures because the compiler knows it doesn’t have to make the variable/function available outside the module – allowing the function to be inlined for example.

Leave a Comment