• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 396
  • Last Modified:

Is it guaranteed by modern C++ compilers that a caste from bool to double will always result only in 0.0 or 1.0?

double d;
bool b;
int i;

b = true:
d = (double) b;

// how about
i = 2;
b = (bool) i;
d = (double) b;
     
0
47pitch
Asked:
47pitch
2 Solutions
 
for_yanCommented:


see here:
http://msdn.microsoft.com/en-us/library/aa325135%28v=vs.71%29.aspx

public: static double ToDouble(
 bool value
);

The number 1 if value is true; otherwise, 0.
0
 
for_yanCommented:

http://bytes.com/topic/c/answers/674697-bool-int-cast
From bool to int, false is always 0, true is always 1.
From int to bool, 0 is always false, anything other than 0 is true.


// how about
i = 2;
b = (bool) i;
d = (double) b;

therefore d should become 1.0

as b becomes true
and then it is cast to double as 1.0


0
 
for_yanCommented:
I actually tried this, using gcc compiler on solaris
and got expected result : 1.000

I think such things should be fairly standardized
 

#include <stdio.h>
#include <stdbool.h>

void main(){
int i;

double d;
bool b;
i =2;
b = (bool) i;
d = (double) b;
printf("%3f\n",d);

}

Open in new window

0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
Subrat (C++ windows/Linux)Software EngineerCommented:


Compiler implicitly do the casting for you.

But better to use static_cast instead of simple c style casting.
Ex:
b = static_cast<bool>(i);
d = static_cast<double>(b);
0
 
evilrixSenior Software Engineer (Avast)Commented:
>> I think such things should be fairly standardized

Actually, the result is very well defined as far as the standard is concerned...

4.9 Floating-integral conversions

An rvalue of an integer type or of an enumeration type can be converted to an rvalue of a floating point
type. The result is exact if possible. Otherwise, it is an implementation-defined choice of either the next
lower or higher representable value. [Note: loss of precision occurs if the integral value cannot be represented
exactly as a value of the floating type. ] If the source type is bool, the value false is converted to
zero and the value true is converted to one.
0
 
47pitchAuthor Commented:
Thanks!
I was looking for authoritative reference to show my colleagues
0

Featured Post

How to Use the Help Bell

Need to boost the visibility of your question for solutions? Use the Experts Exchange Help Bell to confirm priority levels and contact subject-matter experts for question attention.  Check out this how-to article for more information.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now