Search code examples
cif-statementoperator-precedence

AND and OR operator c


Hey i am working on a code and i stuck inside this if condition which is (Not a actual Code simplified for better understanding)

if(18&2==2)
do something;

this if condition not executing but if i write like this

if(18|2==18)
do something;

it executed normal

also when I,

printf("%d",18&2);

it gives 2 now i am so confused why the above if statement not executing, is it because of precedence ,please explain thanks.


Solution

  • Yours is a precedence "error". The bit-wise operators have lower precedence than equality. Making 18 & 2 == 2 into 18 & (2 == 2), which is 18 & 1. That last one obviously evaluates to 0, since 18 is divisible by 2.

    In such cases, when you get "weird results". Start by adding parenthesis to make sure every operator operates on the operand you expect it too.