Why are global variables always initialized to '0', but not local variables?

yuvanesh picture yuvanesh · Dec 27, 2012 · Viewed 71.2k times · Source

Possible Duplicate:
Why are global and static variables initialized to their default values?

See the code,

#include <stdio.h>

int a;
int main(void)
{
    int i;
    printf("%d %d\n", a, i);
}

Output

0 8683508

Here 'a' is initialized with '0', but 'i' is initialized with a 'junk value'. Why?

Answer

K-ballo picture K-ballo · Dec 27, 2012

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.