Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does C++ initialize integers to zero automatically?

Tags:

c++

coverity

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?

like image 909
PerryC Avatar asked Jul 13 '15 17:07

PerryC


3 Answers

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.

like image 133
R Sahu Avatar answered Oct 12 '22 07:10

R Sahu


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.

like image 13
SigTerm Avatar answered Oct 12 '22 05:10

SigTerm


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:
— if T is a (possibly cv-qualified) class type (Clause 9), the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor);
— if T 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

like image 1
jxh Avatar answered Oct 12 '22 06:10

jxh