VortixDev
VortixDev

Reputation: 1013

Result of bitwise AND appears to be 0, but isn't

I've got the following situation:

#include <stdio.h>

int main(void) {
  int first = 0x08;

  printf("%d\n", first & 0b10);
  printf("%d\n", first & 0b10 == 0);

  if (first & 0b10 == 0) {
    printf("SET");
  } else {
    printf("NOT");
  }

  return 0;
}

Two 0s print out, followed by NOT. What is happening here? It seems to be that first & 0b01 is zero, so should pass the condition.

Upvotes: 0

Views: 80

Answers (3)

fetag
fetag

Reputation: 174

because == has higher precedence than &.

Here is the reference: Operator Precedence

Upvotes: 1

Alex Lop.
Alex Lop.

Reputation: 6875

This is called operator precedence.

first & 0b10 == 0

First evaluated:

0b10 == 0  // which is false ==> 0

Then

first & 0  // which is also 0

To get the result you expect use parenthesis to force the order of evaluation:

(first & 0b10) == 0  // this will true ==> 1

Upvotes: 2

dbush
dbush

Reputation: 223689

This is an issue of operator precedence.

The bitwise AND operator & has lower precedence than the equality operator ==. So this:

first & 0b10 == 0

Is the same as:

first & (0b10 == 0)

Which is not what you want. It compares 0b10 for equality with 0, which is false. Then first & 0 is evaluated which is 0.

Add parenthesis to get the desired behavior:

(first & 0b10) == 0

Upvotes: 3

Related Questions