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.
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.
bool is an integral type, and value-intialization should make it zero.
Is the variable b always initialized with false or true?
false
Converting true
to an integer
type will yield 1
, and converting false
will yield 0
(4.5/4
and 4.7/4
)
A very simple test code
#include<iostream>
int main()
{
bool b=bool();
if(!b)
{
std::cout<<"b: false";
}
}
The b is initialized also with zero.
bool behaves 'as if it were declared':
enum bool {false,true};
It is an integral type and might be casted to int as values 0 and 1 (respectively), and its default value is false.