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

Discussion

Predict the output of following program.

#include <stdio.h>

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

 

  • A.x= 10
  • B.x= 8
  • C.x= 12
  • D.x= 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.

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

Post your comment

Please log in or register to post a comment.