"Global variables" are defined in the file area outside any function. All variables defined in the file area and all variables declared with the static have something called static storage duration. This means that they will be allocated in a separate part of the memory and will exist throughout the entire duration of the program.
This also means that they are guaranteed to be initialized to zero on any C compiler.
From the current C11 standard 6.7.9 / 10:
"... If an object that has a static or storage duration of threads is not initialized explicitly, then:
- if it has a pointer type, it is initialized with a null pointer;
- if it has an arithmetic type, it is initialized (positive or unsigned) to zero; "
In practice, this means that if you initialize your global variable with a given value, it will have that value and will be allocated in a memory segment, usually called .data . If you do not give it a value, it will be highlighted in another segment called .bss . Globals will never be allocated on the stack.
source share