views:

119

answers:

5

Hi alltogether,

I am just wondering, which value the default constructor of bool type returns in C++. For instance writing such a code

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. Can anyone help me?

Thanks in advance

+4  A: 

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

DeadMG
+1: integral types don't have a constructor in C or C++, that's a Java-ism.
rubenvb
+7  A: 

false.

[adding characters 'cause of the limit]

Alexandre C.
I've +1'ed this one, because it's the oldest answer that correctly gives a boolean value as the result. Confusing "zero" with "false" is widely common in C++. :(
Johannes Schaub - litb
A: 

The b is initialized also with zero.

Vash
+3  A: 

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";
  }

}
Prasoon Saurav
C++ is full of "undefined behavior" things which make such experimentation dangerous.
Alexandre C.
Why do you think the behavior of the above code is undefined?
Prasoon Saurav
it isn't, by your quoting of the Holy Standard. But one should not get confidence that something is standard by making it work on its own machine.
Alexandre C.
@Alexandre C.: Yups, rightly said. :)
Prasoon Saurav
Why a downvote?
Prasoon Saurav
@Alexandre C: I fully agree. This kind of test code is just wrong.
DeadMG
@DeadMG: the answer had been edited to avoid misleading readers though.
Alexandre C.
@DeadMG: I don't understand what are you trying to say, be more specific.
Prasoon Saurav
A: 

bool behaves 'as if it weer declared':

enum bool {false,true};

It is an integral type, might be casted to int as values 0 and 1 (respectively) and its default value is false.

Zara