Thought Leadership

Static or static

By Colin Walls

In English, the word “static” has a variety of meanings, but they can be summed up by the definition of the adjective: “pertaining to or characterized by a fixed or stationary condition”. In the software world, it generally refers to things that do not change over time. In both cases, the opposite may be “dynamic”.

In C and C++, the keyword static is inspired by the broader meaning of the word, but has two, separate uses. In C++, there is even a third use of the keyword. The nuances of these meanings/uses are not always well understood …

In C/C++, when you declare a variable [or instantiate an object], the location of the declaration implies the scope of the variable and where in memory it is stored. For example:

int x;
void fun()
{
   int y;
   ...

The variable x has a scope which renders it visible to any function following it in this module and any function in any other module. It is stored in static memory – i.e. not on the stack or in a register. The variable y is only available within the function fun() and is stored on the stack or in a register.
If we modify the code thus:

static int x;
void fun()
{
   static int y;
   ...

The scope of x is now restricted to functions following it in this module and it is not available to functions outside of this module. Its storage is unchanged. The scope of y is unchanged, but it is now stored in static memory.
Notice how the same keyword changed the scope of an external variable and the storage of an automatic variable, even though these are quite different attributes of the variables. I feel that an addition keyword local would be useful to adjust the scope of an external variable.
In C++, there is a third use for the static keyword. It can be used to share a member variable among instances of a class. For example:

class c
{
   static int z;
   ...

In every instantiation of class c, the member variable z is shared; i.e. it refers to the same storage location.
If you are interested in more information this topic, I authored a tech paper which was published recently and may be useful.

Leave a Reply

This article first appeared on the Siemens Digital Industries Software blog at https://blogs.sw.siemens.com/embedded-software/2010/06/01/static-or-static/