Default constructor value for bool type

▼魔方 西西 提交于 2020-01-02 00:15:33

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!