What is printed by this C code: printf(“%d”, 40 & (40 – 1));?
Correct answer D. 32
Explanation
40 is 101000 in binary and 39 is 100111. ANDing them clears the lowest set bit of 40, leaving 100000, which is 32. The expression x & (x - 1) always removes the lowest 1 bit, so it is 0 exactly when x is a power of two (or zero). Repeating it until x becomes 0 counts the set bits, a technique known as Kernighan's method.
Answer checked How we write and check questions
Discussion