C++ Bool Returns 0 1 Instead of True False

C++ bool returns 0 1 instead of true false

You can use std::boolalpha:

Sets the boolalpha format flag for the str stream.

When the boolalpha format flag is set, bool values are
inserted/extracted as their names: true and false instead of integral
values.

This flag can be unset with the noboolalpha manipulator.

The boolalpha flag is not set in standard streams on initialization.

std::cout.setf(std::ios::boolalpha);
std::cout << true;

or

std::cout << std::boolalpha << true;

Why is my bool return statement returning something other than 0 or 1?

Looks like your attempt to implement recursive function is not correct.

isHappy(sumSquares);

should probably be

return isHappy(sumSquares);

Is C/C++ bool type always guaranteed to be 0 or 1 when typecast'ed to int?

Yes:

In C++ (§4.5/4):

An rvalue of type bool can be
converted to an rvalue of type int,
with false becoming zero and true
becoming one.

In C, when a value is converted to _Bool, it becomes 0 or 1 (§6.3.1.2/1):

When any scalar value is converted to
_Bool, the result is 0 if the value compares equal to 0; otherwise, the
result is 1.

When converting to int, it's pretty straight-forward. int can hold 0 and 1, so there's no change in value (§6.3.1.3).

C++: Can you return values of 0 or 1 as false and true in boolean functions?

Yes, because 0 will be implicitly converted to false and 1 (or any other nonzero value) will be implicitly converted to true.

Not everything legal is a good idea, however.

C99 - why are false and true defined as 0 and 1 and not as ((bool)0) and ((bool)1)?

false and true are defined as the integer constants 0 and 1 respectively, because that's exactly what the C99 standard specifies in section 7.16 :

< SNIP >

The remaining three macros are suitable for use in #if preprocessing directives. They
are

true

which expands to the integer constant 1,

false

which expands to the integer constant 0, and

< SNIP >

EDIT : as the comments below indicate, it seems I slightly misinterpreted the question, and I should have provided the reason the standard specifies it like that. One reason I can think of, is that true and false are supposed to be usable in #if preprocessing directives (as the quote from the standard mentions).

The reason ((bool) 0) or ((bool) 1) won't work in #if preprocessing directives, is because the standard doesn't allow it. In section 6.10.1 it says :

The expression that controls conditional inclusion shall be an integer constant expression
except that: it shall not contain a cast;



Related Topics



Leave a reply



Submit