C if-else semantics: Which of the following are correct?\n1) Every if-else statement can be replaced by an equivalent expression using the ?: (conditional) operator.\n2) Nested if-else statements are allowed.\n3) Multiple statements are permitted inside an if block.\n4) Multiple statements are permitted inside an else block.

Difficulty: Easy

Correct Answer: 2, 3, 4

Explanation:


Introduction / Context:
This item distinguishes statement-level control flow (if/else) from expression-level selection (the conditional operator ?:), and confirms legality of nesting and multiple statements within blocks.



Given Data / Assumptions:

  • Standard C syntax with braces { } forming compound statements.
  • ?: produces a value; if/else controls statements.


Concept / Approach:
(2) is true: you can nest if-else arbitrarily. (3) and (4) are true: place multiple statements inside { } to form a single compound statement. (1) is false as stated: while many simple if/else constructs can be expressed with ?:, not “every” one can be replaced cleanly; ?: requires expressions for both arms and is unsuitable for certain statement-only flows or declarations with scope needs.



Step-by-Step Solution:
Recognize if (cond) { s1; s2; } else { t1; t2; } as legal with multiple statements.Note that (cond) ? expr1 : expr2 must yield a value; not all statement blocks translate directly to a single expression.Nesting: if (a) if (b) ... else ... is permitted; beware of the dangling-else rule.



Verification / Alternative check:
Attempt to replace complex blocks with ?:; you will often need comma operators or compound literals, which harms clarity and may not be equivalent.



Why Other Options Are Wrong:
Any option including (1) overgeneralizes. Options lacking either (3) or (4) ignore basic block semantics.



Common Pitfalls:
Forgetting braces leading to unintended binding; misusing ?: when side effects and declarations are involved.



Final Answer:
2, 3, 4

Discussion & Comments

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