Search code examples
cglobal-variables

Are global variables always initialized to zero in C?


#include <stdio.h>
int a[100];
int main(){
    printf("%d",a[5]);
    return 0;
}

Does the above code always print '0' or is it compiler specific? I'm using gcc compiler and I got the output as '0'.


Solution

  • Yes, all members of a are guaranteed to be initialised to 0.

    From section 3.5.7 of the C89 standard

    If an object that has static storage duration is not initialized explicitly, it is initialized implicitly as if every member that has arithmetic type were assigned 0 and every member that has pointer type were assigned a null pointer constant.