Background: Global and static variables were introduced in C to store data outside the local context of functions. Automatic pre-initialization and placement in special sections of the executable file optimize program performance, but can also lead to less obvious behavior if not understood.
Issue: It is important to know that global and static variables in C are initialized either with an explicitly defined value or automatically to zero (Zero Initialization). Initialization occurs before the execution of main, which reduces the risk of accessing uninitialized data, but under certain conditions can lead to unexpected dependencies related to the initialization of multiple modules and the order of their loading.
Solution:
Example code:
#include <stdio.h> static int stat_var; int glob_var = 42; int main() { printf("static: %d, global: %d\n", stat_var, glob_var); }
Key features:
1. Can you rely on implicit zeroing of static variables and consider it a safe practice?
Technically it works, but in large projects it's better to explicitly initialize variables for readability and to prevent potential changes in compilers/linkers.
2. What will happen if a static variable is declared in an external function without initialization?
It will still be initialized to zero: static int value; will always equal 0 at runtime.
3. When does the initialization of a global variable with an initializer occur if the variable is declared in a separate isolated module?
Initialization occurs before main is called, but the standard does not guarantee the order of initialization for such variables between different modules, which can lead to accessing uninitialized data in the constructor of another module.
A developer declared static variables to store shared state, assuming they would always be explicitly initialized.
Pros:
Cons:
After a review, variables were explicitly initialized at the point of declaration.
Pros:
Cons: