C language theory: Which of the following statements about for, while, and do-while is/are correct?\n1) A for loop always runs faster than a while loop.\n2) Anything achievable with a for loop can also be written using a while loop.\n3) The construct for(;;); creates an infinite loop.\n4) A for loop guarantees at least one execution of the loop body.

Difficulty: Easy

Correct Answer: 2 and 3

Explanation:


Introduction / Context:
Loop constructs in C are semantically similar; differences are primarily in syntax and typical usage patterns. This question probes common misconceptions about performance and execution guarantees.



Given Data / Assumptions:

  • Plain, portable C without compiler-specific optimizations assumed.
  • Statements are general claims about the language, not about a specific compiler.


Concept / Approach:
(2) is true: for and while are interchangeable by re-expressing initialization, condition, and increment. (3) is true: for(;;) is the canonical infinite loop; adding a trailing semicolon makes the loop body an empty statement. (1) is false: any performance difference is a matter of optimization; the standard gives no timing guarantees. (4) is false: “at least once” is the property of do-while; for and while may execute zero times if the condition is initially false.



Step-by-Step Solution:
Map for(init; cond; step) { body } to while(cond) { body; step } with init before.Recognize for(;;) as while(1) with no built-in exit.Note that for checks its condition before the first iteration.



Verification / Alternative check:
Compile examples showing one-to-one conversion between constructs; benchmark results vary by compiler and flags, disproving a universal speed rule.



Why Other Options Are Wrong:
Options including (1) assume guaranteed speed differences. Options including (4) confuse for with do-while.



Common Pitfalls:
Equating idiomatic use with semantics; forgetting that an empty loop body still consumes CPU; assuming compilers always generate jump tables for loops.



Final Answer:
2 and 3

Discussion & Comments

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