Are you asking because you saw somebody else's code using the "static" keyword for the definition of a variable with block scope?
It is entirely legal in C (and I assume C++) for a block-scope variable to be declared "static". Such a variable declaration has the following implications:
1. If there is an explicit initializer, then the variable is assigned that value only once, before any part of your program gets to run. Compare this behavior to an explicitly initialized automatic variable -- the automatic variable is initialized each time you enter the block.
2. If there is no explicit initializer, then the variable is assigned the value 0 (zero) only once, before any part of your program gets to run. Compare this behavior to an automatic variable lacking an initializer -- the automatic variable has an unpredictable initial value.
3. The variable can only be accessed from within the block. Each time you enter the block the variable has the same value it had the last time you left the block. Compare this behavior to an automatic variable -- the value of the automatic variable upon entry to the block depends on its initializer as described in #1 and #2 above.
4. In a multi-threaded application, all threads refer to a single common instance of this variable. (Compare this to automatic variables, where each thread has its own separate and independent set of automatic variables.) This can be useful, because it provides a way for the threads to communicate with each other; and it can be dangerous, because it provides a way for the threads to interfere with each other.
Sometimes I will use the following idiom to insure that certain one-time initialization takes place. With this approach I don't have to rely on the user to call an initialization function first. I probably wouldn't use this idiom for multi-threaded code.
- void func(void) {
-
static int isInitialized = 0;
-
if (! isInitialized) {
-
funcInit();
-
isInitialized = 1;
-
}
-
<do something useful>
-
}