Does gcc automatically initialize static variables to zero?

Yes – the C standard ISO/IEC 9899:1999 a.k.a. C99 (and C++) standards say this must be so. See item 10 in section 6.7.8 (“Initialization”) of WG14 N1256 for the exact text.

As others have pointed out, it is good practice to always initialise static variables:

static int idx = 0;

The reason for doing this is not because some compiler might not always initialise static variables to zero (any compiler that failed to do such initialisation would be terminally broken, and could not claim to be a C or C++ compiler), it is to Say What You Mean – possibly the most basic rule of programming.

Leave a Comment