Condition checking gives wrong answer

49 Views Asked by At
#include <stdio.h>
int main(){
  printf("%d,%d\n", 2 & (1<<1) , 2 & (1<<1)>0 );
  return 0;
}

the output of this program is 2,0.

2 & (1<<1) is equal to 2 which is more than 0. so why does 2 & (1<<1) > 0 evaluate to zero??

1

There are 1 best solutions below

0
On

This expression

2 & (1<<1)>0

is equivalent to

2 & ( (1<<1)>0 )

due to the precedence of the operators. That is the relational operator > has a higher precedence than the bitwise AND operator. As 1 << 1 is greater than 0 then the sub-expression ( ( 1 << 1 ) > 0 ) yields the value 1.

So 2 & 1 yields 0 because in binary 1 can be represented (for simplicity) like 01 and 2 - like 10 and

 01
&
 10
---
 00

It seems what you mean is the following expression

( 2 & ( 1 << 1 ) ) > 0