Difference between static global variable and non-static global variable in C [duplicate]

There are basically four cases:

  • declared outside of function, without static
  • declared outside of function, with static
  • declared inside of function, without static
  • declared inside of function, with static

Let’s cover these in turn.

Declared outside of function, without static

This is a conventional global symbol. You can access it from any source file (although in that other source file, you typically need an extern declaration).

Declared outside of function, with static

This is the “static” global you were asking about. You can access it only within the source file where it is defined. It’s “private” to that source file, but you can access it from any function in that source file (well, actually, any function in that source file that occurs below its declaration). Like any global variable, it maintains its value for the life of the program.

Declared inside of function, without static

This is a conventional local variable. You can access it only within that function. Each time the function is called (including recursively), you get a new instance of the variable. If you don’t initialize it, it starts out containing an unpredictable value. It does not maintain its value between calls.

Declared inside of function, with static

This is a static local variable. You can access it only within that function. There is exactly one copy of it, shared between all calls to the function (including recursive calls). If you don’t initialize it, it starts out zero. It maintains its value between calls.

In three of these cases, if you don’t provide an explicit initializer, a variable is guaranteed to be initialized to 0. But in the case of true local variables, if you don’t provide an explicit initializer,
it starts out containing an unpredictable value, which you can’t depend on.

Formally, there are two concepts here, visibility and lifetime. True global variables are visible anywhere in the program. Static global variables are visible only in their source file. Local variables are visible only in their function. All global variables, and all static variables, have static duration — they last for as long as the program does. (Also these are the ones that are guaranteed to be initialized to 0.) True local variables have “automatic” duration — they come and go as the containing function is called and returns.

Closely related to duration is the question of where variables will actually be stored. Static-duration variables are typically stored in the data segment. Automatic-duration variables are typically — though not necessarily — stored on the stack.

Leave a Comment