Abhishek Gupta
Abhishek Gupta

Reputation: 157

How this bitwise operation work?

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

Answers (4)

claudio06
claudio06

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

Slava
Slava

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

AhmadWabbi
AhmadWabbi

Reputation: 2197

Because == has precedence over &. So, Your expression is equivalent to:

( 8 & (7==0))

which equals 0.

Upvotes: 5

Alex Lop.
Alex Lop.

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

Related Questions