3

Please help to solve this problem and explain the logic. I don't know how the & operator is working here.

void main() {
   int a = -1;
   static int count;
   while (a) {
      count++;
      a &= a - 1;
   }
   printf("%d", count);
}
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
user302593
  • 123
  • 2
  • 13

4 Answers4

5

If you are referring to

a&=a-1;

then it is a bitwise and operation of a and a-1 copied into a afterwards.

Edit: As copied from Tadeusz A. Kadłubowski in the comment:

a = a & (a-1);
Tobias Wärre
  • 793
  • 5
  • 11
3

The expression a&=a-1; clears the least significant bit (rightmost 1) of a. The code counts the number of bits in a (-1 in this case).

Starting from

a = -1 ; // 11111111 11111111 11111111 11111111 32bits signed integer

The code outputs 32 on an 32 bit integer configuration.

Tugrul Ates
  • 9,451
  • 2
  • 33
  • 59
2

& is the bitwise and operator.

The operation

a&=a-1;

which is same as:

a = a & a-1;

clears the least significant bit of a.

So your program effectively is calculating the number of bits set in a.

And since count is declared as static it will automatically initialized to 0.

codaddict
  • 445,704
  • 82
  • 492
  • 529
0

you have count uninitialized

should be

static int count=0;

operator & is called AND http://en.wikipedia.org/wiki/Bitwise_operation#AND

fazo
  • 1,807
  • 12
  • 15
  • The C standard guarantees that static variables are initialized to zero if the programmer didn't init them explicitly. Regardless, good practice is that the program either initialize them explicitly or assign a value to them before using them. – Lundin Mar 04 '11 at 10:20
  • I tried to contradict you on this above and realised my mistake after looking at the C specification. The relevant portion is 6.7.8.10 if anyone else happens to be looking. – James Greenhalgh Mar 04 '11 at 10:52