Chained relational operators in C: how is this expression evaluated?
#include
int main()
{
int x = 10, y = 20, z = 5, i;
i = x < y < z; // left-to-right evaluation with boolean 0/1
printf("%d
", i);
return 0;
}
-
A0
-
B1
-
CError
-
DNone of these
-
EImplementation-defined
Answer
Correct Answer: 1
Explanation
Introduction / Context:C does not support mathematical chained comparisons like some languages. Instead, relational operators are evaluated left-to-right, and each comparison yields either 0 (false) or 1 (true). Understanding this prevents logic mistakes.
Given Data / Assumptions:
- x = 10, y = 20, z = 5
- Expression: x < y < z
- C relational operators yield int 0 or 1.
Concept / Approach:Evaluation: x < y is 10 < 20 → 1. Then we evaluate 1 < z which is 1 < 5 → 1. Therefore, the final result assigned to i is 1.
Step-by-Step Solution:Compute x < y → 1.Then evaluate (1) < z → 1 < 5 → 1.Assign i = 1 and print it.
Verification / Alternative check:To express a mathematical chain correctly, use logical AND: (x < y) && (y < z). With z=5 that expression would be true && false → 0, differing from the chained form.
Why Other Options Are Wrong:A/D/E mischaracterize the deterministic result. C: It is valid C, not a syntax error.
Common Pitfalls:Assuming C treats chained comparisons like mathematics; forgetting that intermediate boolean becomes 0/1 and participates in the next comparison.
Final Answer:1