Machine-translated by Google. Questions are authored in English.
Top

Discussion

What will be the output of the program?

#include <stdio.h>

int main()
{
    int x = 10;
    printf("%d", x & (x - 1));
    return 0;
}

  • A.8
  • B.10
  • C.2
  • D.0

Answer: C

Correct answer: 8

The expression x & (x - 1) is a well-known idiom: it clears the lowest set bit of x.

Here \( x = 10 \), which is 1010, so \( x - 1 = 9 \), which is 1001. Subtracting one flips the lowest set bit to 0 and turns every zero below it into a 1 - that is what borrowing does in binary. ANDing the two therefore agrees on everything above that bit and disagrees at it and below:

  10 = 1 0 1 0
   9 = 1 0 0 1
  -----------
   & = 1 0 0 0

The result 1000 is 8.

The idiom has two common uses. Repeating it until the value reaches zero counts the set bits in as many steps as there are ones - Kernighan’s algorithm. And a single application testing x & (x - 1) == 0 identifies a power of two, since only those have exactly one bit set.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.