Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default constructor value for bool type

Tags:

Which value does the default constructor of the bool type return in C++?

For instance, writing

int i = int(); 

guarantees that the variable i will be initiated always with 0.

I guess such an initialization routine is possible as well:

bool b = bool(); 

But unfortunately I could not find anywhere which value such a default bool constructor is defined to return. Is the variable b always initialized with false or true.

like image 493
Necip Avatar asked Jul 22 '10 10:07

Necip


People also ask

What is the default value of bool?

The default value of the bool type is false .

What is the default value of constructor?

The default constructor in Java initializes the data members of the class to their default values such as 0 for int, 0.0 for double etc. This constructor is implemented by default by the Java compiler if there is no explicit constructor implemented by the user for the class.

What is default value of bool in C++?

The default value of boolean data type in Java is false, whereas in C++, it has no default value and contains garbage value (only in case of global variables, it will have default value as false).

Is bool always 0 or 1?

Boolean values and operations They are used as the values of expressions that have yes-or-no answers. C++ is different from Java in that type bool is actually equivalent to type int. Constant true is 1 and constant false is 0.


2 Answers

false.

Seen in the C++14 draft N4296, section 8.5 (Initializers), paragraph 6, list item 1 and references therein, and paragraph 8, list item 4.

like image 139
Alexandre C. Avatar answered Sep 22 '22 14:09

Alexandre C.


bool is an integral type, and value-intialization should make it zero.

like image 29
Puppy Avatar answered Sep 20 '22 14:09

Puppy