Why are global variables always initialized to '0', but not local variables? [duplicate]
Because that's the way it is, according to the C Standard. The reason for that is efficiency:
static variables are initialized at compile-time, since their address is known and fixed. Initializing them to
0
does not incur a runtime cost.automatic variables can have different addresses for different calls and would have to be initialized at runtime each time the function is called, incurring a runtime cost that may not be needed. If you do need that initialization, then request it.
global
and static
variables are stored in the Data Segment (DS) when initialized and block start by symbol (BSS)` when uninitialized.
These variables have a fixed memory location, and memory is allocated at compile time.
Thus global
and static
variables have '0'
as their default values.
Whereas auto
variables are stored on the stack, and they do not have a fixed memory location.
Memory is allocated to auto
variables at runtime, but not at
compile time. Hence auto
variables have their default value as garbage.