31

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

static int idx;
Amjith
  • 22,626
  • 14
  • 43
  • 38

2 Answers2

39

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.

Adam Spiers
  • 17,397
  • 5
  • 46
  • 65
  • 1
    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. – ephemient Aug 18 '09 at 16:17
  • 5
    I don't see why that should be the case. The compiler can easily ignore explicit zero initialisations. –  Aug 18 '09 at 16:21
  • 3
    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... – ephemient Aug 18 '09 at 18:19
  • 4
    @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. – Nick Oct 14 '15 at 09:56
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.

AAA
  • 4,928
  • 1
  • 24
  • 20
  • 5
    And it also makes it clear to future developpers that you need the value to be zero. – Edd Aug 18 '09 at 15:55
  • 6
    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. – Marsh Ray Aug 18 '09 at 16:00
  • 1
    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. – underscore_d Jun 14 '17 at 21:41