3) Static variables (like global variables) are initialized as 0 if not initialized explicitly. For example in the below program, value of x is printed as 0, while value of y is something garbage.
Global and static variables are initialized to their default values because it is in the C or C++ standards and it is free to assign a value by zero at compile time. Both static and global variable behave same to the generated object code.
If you declare a static variable in a class, if you haven't initialized them, just like with instance variables compiler initializes these with default values in the default constructor.
Example# In the absence of explicit initialization, external and static variables are guaranteed to be initialized to zero; automatic variables (including register variables) have indeterminate1 (i.e., garbage) initial values.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With