I've noticed several Coverity (static-analysis tool) errors of type 'Uninitialized scalar variable' that are high impact. A lot of them are just ints that don't get initialized.
Would initializing them to zero be any different than what C++ does by default?
Does C++ initialize integers to zero automatically?
For automatic variables:
Some compilers might do it but the standard does not require it. A conforming implementation could leave them to be uninitialized garbage values.
For static
variables:
They must be initialized to zero unless explicitly initialized otherwise.
C++ does not initialize integer variables to zero by default.
Some compilers may zero them out or fill with some default value while compiling your project in debug mode. In release mode that usually does not happen.
There is an exception with static variables, but by default it is safe to assume that anything unitialized holds a random value.
Beware of uninitialized variables. Finding this kind of bug is hard and can waste a lot of time. Usual symptoms: the program works fine in debug mode, but behaves strangely in release.
Objects declared in static storage duration are zero initialized before any other initialization takes place (including default initializations).
To default-initialize an object of type
T
means:
— ifT
is a (possibly cv-qualified) class type (Clause 9), the default constructor forT
is called (and the initialization is ill-formed ifT
has no accessible default constructor);
— ifT
is an array type, each element is default-initialized;
— otherwise, no initialization is performed
C.11 §8.5¶6[ Note: Every object of static storage duration is zero-initialized at program startup before any other initialization takes place. In some cases, additional initialization is done later. — end note ]
C.11 §8.5¶9
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