Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

comparison operator values C++

We all know C++ (while not a superset) is pretty much derived from C.

In C++, the operators <, <=, >, >=, ==, and != all have boolean return values. However, in C, the same operators returned 1 or 0, since there was no 'bool' type in C.

Since all integer values except 0 are treated as "true", and 0 is "false", I want to know:

Does C++ still restrict the return values of the operators to be 1 vs 0, or does a 'true', from one of these operators, return any 1-byte value, so long as it isn't 0?

I want to know since using these return values as explicit 1 or 0 would be useful in bitwise operations without branching.

As a terrible example, take the following:

bool timesTwo;
int value;

//...

if(timesTwo)
    value << 1;

//vs

value << (int) timesTwo;
like image 797
Serge Avatar asked Jul 24 '26 22:07

Serge


2 Answers

Does C++ still restrict the return values of the operators to be 1 vs 0, or does a 'true', from one of these operators, return any 1-byte value, so long as it isn't 0?

The comparison operators, assuming that they have not been overloaded, only ever return true and false.

int(true) is always 1.

int(false) is always 0.

So,

int one(1), two(2);
assert( (one<two) == 1 );
assert( (two<one) == 0 );
like image 109
Robᵩ Avatar answered Jul 27 '26 11:07

Robᵩ


In fact, bool is automatically converted into integer in C++ (1 if true, 0 if false) when used in expressions and there's no need to cast.

value << (int) timesTwo;

The case is not necessary: if `timesTwo`` is true then

you can directly do without a casr:

value<<timesTwo;

which is equivalent to:

value<<1;
like image 27
P.P Avatar answered Jul 27 '26 13:07

P.P



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!