问题
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.
回答1:
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.
回答2:
bool is an integral type, and value-intialization should make it zero.
回答3:
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";
  }
}
回答4:
The b is initialized also with zero.
回答5:
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.
来源:https://stackoverflow.com/questions/3308028/default-constructor-value-for-bool-type