C conditional operator with assignments – behavior and output:\nIs there any error in this program, and what will it print?\n\n#include <stdio.h>\nint main()\n{\n int n = 0, y = 1;\n y == 1 ? n = 0 : n = 1;\n if (n)\n printf("Yes\n");\n else\n printf("No\n");\n return 0;\n}

Difficulty: Easy

Correct Answer: None of above

Explanation:


Introduction / Context:
This question tests whether writing assignments inside the conditional operator is valid C and whether such code compiles without error. It also asks you to infer the resulting output of the program flow.


Given Data / Assumptions:

  • y is 1; thus y == 1 is true.
  • The conditional operator assigns to n either 0 or 1.
  • An if prints “Yes” when n is nonzero, else prints “No”.


Concept / Approach:
The conditional operator ?: chooses one of two expressions. Using assignments as operands is legal. When the condition is true, the left operand executes; otherwise, the right operand executes. Since y == 1 is true, n is set to 0, and the subsequent if (n) evaluates as false, so “No” is printed. There is no declaration or syntax error here; the code is valid and well-formed.


Step-by-Step Solution:
Evaluate condition: y == 1 → true.Execute true branch: n = 0;Test if (n) → false → go to else.Print No.


Verification / Alternative check:
Parenthesizing for readability, y == 1 ? (n = 0) : (n = 1);, produces identical behavior.


Why Other Options Are Wrong:
None of the listed errors apply: the declaration is correct, syntax is valid, and assignments target a proper lvalue (n).


Common Pitfalls:
Assuming the conditional operator requires pure values; it can contain side effects like assignments. Another pitfall is expecting “Yes” because of the true condition, forgetting that the true branch explicitly forces n to 0.


Final Answer:
None of above

More Questions from Control Instructions

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion