Predict the output of following program.
#include <stdio.h>
int main()
{
int x=10;
x &= ~2;
printf("x= %d",x);
return 0;
}
Answer: B
Correct answer: x= 8
This is the clear-a-bit idiom, x &= ~mask. Build the mask first: 2 is \( 0010_2 \), so ~2 is ...11111101 - every bit set except bit 1.
ANDing forces that one position to 0 and leaves the rest untouched:
\[ 1010_2 \mathbin{\&} 1101_2 = 1000_2 = 8 \]
So the operation removes the value 2 from x. The distractor 12 is what x |= 2 would give, and 10 is what would result if the bit had not been set in the first place.
Please log in or register to report this question.