Reputation: 157
This code confuses me a lot:
bool b = 8 & 7 == 0; //b == false
std::cout << 8 & 7; //Outputs 0
Why does it do that?
Upvotes: 3
Views: 99
Reputation: 44
first line has been coverred, for second line since 8 = 1000 and 7 = 0111, the result is 0, whic is expected
Upvotes: 0
Reputation: 44238
Your problem is that expression:
8 & 7 == 0;
is equal to:
8 & ( 7 == 0 );
so to fix it use brackets explicitly:
( 8 & 7 ) == 0;
you should always use brackets when you unsure in evaluation order.
Upvotes: 1
Reputation: 2197
Because ==
has precedence over &
. So, Your expression is equivalent to:
( 8 & (7==0))
which equals 0.
Upvotes: 5
Reputation: 6875
http://en.cppreference.com/w/c/language/operator_precedence
==
is executed/evaluated before &
so you get:
bool b = 8 & 7 == 0; //==>
// 7==0 --> 0
// 8 & 0 --> 0 (which is 'false')
// ==> b is false
To get what you expect just add ()
:
bool b = (8 & 7) == 0; // will be evaluated as 'true'
Upvotes: 8