Reputation: 231
I was playing around with the Bool type (Boolean Variable) and typed this:
#include <iostream>
int main(void)
{
using std::cout;
using std::cin;
using std::endl;
bool $ok = false & true;
if($ok == true)
{
cout << "The value is True." << endl;
}
else if($ok == false)
{
cout << "The value is false." << endl;
}
cin.get();
cin.get();
return 0;
}
I know the differences between using the bitwise operator &
and the logical operator &&
, but I do not see how this produces a false (0) value. I know if I swapped the bitwise operator and used a +
the expression 0+1
would cause it to evaluate to true
. Can someone explain why this:
bool $ok = false & true;
evaluates to false?
Upvotes: 0
Views: 28845
Reputation: 38217
It's because false
is 0 (when converted from boolean-land to integer-land), while true
is 1 (when converted from boolean-land to integer-land).
false & true == 0 & 1 == 0 == false
false + true == 0 + 1 == 1 == true
If the magic of &
is a mystery to you, there are lots of great resources on bitwise-and.
Upvotes: 1
Reputation: 33437
Why would this be true? false
converts to a 0-valued integer. true
converts to a non-zero valued integer (normally 1, but this is not guaranteed). 0 & x
for any x
is always 0
. 0 == false
by definition of the integer/boolean interactions, thus the false branch is entered.
For what it's worth, over a domain of 0 and 1, with 0 as false and 1 as true, *
maps to AND
whereas +
maps to OR
. Given this, I'm not quite sure why you'd expect +
and &
to give the sameresults.
x * y != 0 iff x != 0 and y != 0
x + y != 0 iff x != 0 or y != 0
It's also worth mentioning that bit-wise operations on signed types tend to be a bad idea. If you're going to treat integers as bitfields, use unsigned integral types where the rules around the operations are much more natural and intuitive.
Upvotes: 1
Reputation: 2234
false=0(0x00000000) true=1(0x00000001)
Now when we do bitwise and operator of (false & true)---(0&1=0).
0x00000000
& 0x00000001
-------------
0x00000000
Hence the result is 0(0x00000000)
Upvotes: 5