I have a static variable declared but uninitialized in a function. Will this variable be initialized to zero automatically?
static int idx;
I have a static variable declared but uninitialized in a function. Will this variable be initialized to zero automatically?
static int idx;
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.
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 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.
© 2022 - 2024 — McMap. All rights reserved.