Does gcc automatically initialize static variables to zero?
Asked Answered
T

2

31

I have a static variable declared but uninitialized in a function. Will this variable be initialized to zero automatically?

static int idx;
Titan answered 18/8, 2009 at 15:50 Comment(0)
S
38

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.

Studbook answered 18/8, 2009 at 15:51 Comment(4)
Then again... the argument against explicitly zero-initializing static variables is that it expands the size of the executable, because they won't live in .bss anymore.Burkhalter
I don't see why that should be the case. The compiler can easily ignore explicit zero initialisations.Studbook
Implementation detail. GCC 4.2 and MSVC 7.1 do seem to treat static int a; and static int a = 0; equivalently. I do remember compilers which didn't, but I don't seem to have any on hand that are old enough...Burkhalter
@R.. But you never actually tried that did you? :) Aside from the fact that sizeof(int) * 10000000 < 100 megs (sic), you misunderstand how such declarations are compiled on most C compilers as the executable size will not grow at all and the impact is only at runtime.Firehouse
C
5

While the standards say yes...Good practice indicates that you should always initialise variables. You never know when you change compiler, or have to compile it on another machine, you want to minimise any potential for unexpected behaviour.

Conquest answered 18/8, 2009 at 15:53 Comment(3)
And it also makes it clear to future developpers that you need the value to be zero.Cierracig
double somethingImportant() { static double arr[1024*1024]; ... } Explicit initialization of every member could be a little difficult. If you have a standard compiler, it is initialized by definition. If you can't rely on something basic like that working on your compiler, get another compiler because you will have a difficult time reasoning about any of the code.Kitchen
Yeah, no. Somewhat plausible reasons to always initialise might be for extra clarity or in case the variable is likely to be made non-static soon and you want to avoid problems due to later absent-mindedness. Accommodating crappy compilers that flout the standard isn't a good reason to do anything.Irriguous

© 2022 - 2024 — McMap. All rights reserved.