tags:

views:

734

answers:

2

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

static int idx;
+10  A: 

Yes - the C (and C++) standards say this must be so.

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.

anon
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
I don't see why that should be the case. The compiler can easily ignore explicit zero initialisations.
anon
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
+3  A: 

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.

Jamie Lewis
And it also makes it clear to future developpers that you need the value to be zero.
Edd
@Edd, that it does.
Jamie Lewis
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