Difficulty: Medium
Correct Answer: (a <= 20 ? b : c) = 30;
Explanation:
Introduction / Context:
This question tests your knowledge of the conditional (ternary) operator in C and its ability to yield an lvalue when both operands are lvalues of compatible type. The aim is to remove duplicated constants in assignments by making a single expression that selects which variable should be assigned.
Given Data / Assumptions:
Concept / Approach:
The conditional operator condition ? expr1 : expr2 can yield an lvalue when expr1 and expr2 are both lvalues of compatible type. In that case, the whole conditional expression can appear on the left hand side of an assignment. This allows you to select which variable will receive the assignment before performing a single assignment of the constant. In this example, both b and c are lvalues of the same type, so (a <= 20 ? b : c) is an lvalue expression that can be assigned.
Step-by-Step Solution:
Identify that in the original expression, the only difference between the two branches is whether b or c receives the value 30.
Factor out the common constant 30, leaving a choice between lvalues b and c based on the condition a <= 20.
Write a conditional expression that chooses between these two lvalues: (a <= 20 ? b : c).
Place this conditional expression on the left side of a single assignment: (a <= 20 ? b : c) = 30;.
Verify that when a <= 20, the lvalue is b and b is assigned 30, and when a > 20, the lvalue is c and c is assigned 30.
Verification / Alternative check:
If a is 15, the condition is true, so the expression (a <= 20 ? b : c) selects b as the lvalue and the statement becomes b = 30; matching the original logic. If a is 25, the condition is false, so the expression selects c as the lvalue and the statement becomes c = 30; again matching the original behavior. No other side effects are introduced.
Why Other Options Are Wrong:
Option b attempts to assign to a constant (30), which is illegal because constants are not lvalues and cannot appear on the left side of an assignment.
Option c misuses the comma operator and is not valid syntax for assigning 30 to either b or c conditionally.
Option d combines a conditional and a comparison in a way that does not perform the required assignments and simply checks equality in the false branch.
Common Pitfalls:
Programmers sometimes believe that the conditional operator can only appear on the right side of an assignment, but in C it can yield lvalues under the right conditions. Another pitfall is to write more complex, less readable expressions in the name of brevity. While this rewrite is legal and demonstrates language knowledge, in real world code it might be clearer to keep the explicit if statement for maintainability.
Final Answer:
The expression can be rewritten so that 30 appears only once as (a <= 20 ? b : c) = 30;, which preserves the original logic.
Discussion & Comments