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

Discussion

What will be the output of the following C code?

#include <stdio.h>
    int main()
    {
        if (7 & 8)
        printf("Honesty");
            if ((~7 & 0x000f) == 8)
                printf("is the best policy\n");
    }

 

  • A.Honesty is the best policy
  • B.Honesty
  • C.is the best policy
  • D.No output

Answer: C

Correct answer: is the best policy

Take the two tests separately. \( 7 = 0111_2 \) and \( 8 = 1000_2 \) have no bits in common, so 7 & 8 is 0 and the first printf does not run.

For the second, ~7 inverts every bit, giving ...11111000. Masking with 0x000f keeps only the low four bits, leaving \( 1000_2 = 8 \), so the test is true and is the best policy is printed alone. The mask is what makes the result independent of the width of an int, which is why it is there.

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

Post your comment

Please log in or register to post a comment.