Difficulty: Medium
Correct Answer: a>b ? c=30 : c=40;
Explanation:
Introduction / Context:
The conditional (ternary) operator in C provides a compact, expression-based alternative to simple if/else assignments. It has the form condition ? expr_if_true : expr_if_false and returns the value of one of the two expressions. Using it correctly requires supplying both branches and respecting that it is an expression, not a statement keyword.
Given Data / Assumptions:
Concept / Approach:
A valid ternary expression must include both the true and false branches. It can yield a value, which you may assign or return. Nesting is allowed but parentheses are recommended for readability.
Step-by-Step Solution:
Option (a) provides both branches and performs assignments: a > b ? c = 30 : c = 40; This is valid (though many prefer c = a > b ? 30 : 40; for clarity).Option (b) omits the false branch; it is a syntax error.Option (c) uses nested ternaries to compute a maximum; while complicated, the snippet is missing a final semicolon in this listing but the expression form is otherwise valid. However, the question asks for the correct usage among the listed lines as-is; (a) is the clean, unambiguous example.Option (d) uses “a:b” inside parentheses, which is invalid; it should be return (a > b) ? a : b;
Verification / Alternative check:
Compile variant forms: c = a > b ? 30 : 40; and confirm behavior matches the equivalent if/else.
Why Other Options Are Wrong:
Common Pitfalls:
Forgetting the else part; writing side-effect-laden branches that reduce readability; mixing statements and expressions improperly.
Final Answer:
a>b ? c=30 : c=40;.
Discussion & Comments