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()
    {
        int y = 1;
        if (y & (y = 2))
            printf("true %d\n", y);
        else
            printf("false %d\n", y);
 
    }

 

  • A.true 2
  • B.false 2
  • C.either true 2 or false 2
  • D.true 1

Answer: A

Correct answer: true 2

& is the bitwise AND, so unlike && it does not short-circuit and both operands are evaluated. The assignment sets y to 2 and yields 2, so the test is a non-zero value and the true branch runs, printing the current value of y, which is now 2.

One caution is worth stating: reading y in the left operand is unsequenced with respect to the assignment in the right, which the C standard leaves undefined. Compilers in practice produce true 2, but the expression is one to recognise as badly formed rather than to imitate.

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

Post your comment

Please log in or register to post a comment.