Keval
Keval

Reputation: 65

C++ Logical AND Operator

I am trying to use the logical AND operator, but am getting some an unexpected behavior.

#include <iostream>

using namespace std;

int main() {
  unsigned flags = 0;
  cout << "flags = " << flags << endl;
  for(int i=0; i<3; ++i) {
    flags &= (1 << i);
    cout << "Anding with " << (1 << i) << endl;
    cout << "flags = " << flags << endl;
  }
  return 0;
}

Actual output:

flags = 0
Anding with 1
flags = 0
Anding with 2
flags = 0
Anding with 4
flags = 0

Expected output:

flags = 0
Anding with 1
flags = 1
Anding with 2
flags = 3
Anding with 4
flags = 7

Note that I can get the expected output by simply replacing & with + in my program. But I wanted to know what is that I am doing wrong here?

Upvotes: 0

Views: 1037

Answers (2)

Rook
Rook

Reputation: 6145

This is a common mistake with bitwise and... people assume a & b means "return all the bits of a combined with all the bits of b... it doesn't. It means "return the bits that are set in both a and b".

If a is 1, and b is 2, the binary representations are 01 and 10... no bits in common! The result will of course be 0.

What you need to be using is bitwise or. a | b means "return all the bits that are set in either a or b.

If a is 1, and b is 2, the binary representations are 01 and 10, and so the result is 11 or the 3 you expected.

It may help to think of these operations as the set operations "intersection" and "union", rather than the binary operations "and" and "or".

Upvotes: 8

lrineau
lrineau

Reputation: 6274

You have mixed up | and &. Your expected result corresponds to the iteration of:

 flags |= (1 << i);

The bitwise OR in |= will "add" bits to your bitset flags, whereas the bitwise AND can only remove bits.

Upvotes: 2

Related Questions