Empty for-loop control fields in C: is for(;;) valid and what does this program do? #include<stdio.h> int main() { int i=1; for(;;) { printf("%d ", i++); if(i>10) break; } return 0; }

Difficulty: Easy

Correct Answer: No error

Explanation:

Introduction / Context:This item validates knowledge that C allows empty initialization, condition, and increment expressions in for. A for(;;) is an idiomatic infinite loop, equivalent to while(1), often used with an internal break.

Given Data / Assumptions:

  • i starts at 1.
  • The loop prints i and increments it each time.
  • The loop breaks when i becomes greater than 10.

Concept / Approach:With no condition expression, the second field of the for-loop defaults to “true,” so the loop is infinite unless control is transferred using break, return, or goto. Here a conditional break is used to terminate.

Step-by-Step Solution:First iteration prints 1 (then i=2).The loop prints consecutive integers.When i was printed as 10, it then increments to 11.Check if(i > 10): 11 > 10 → true → break, loop ends.Therefore the program prints 1 through 10, each on a new line, and exits normally.

Verification / Alternative check:Rewrite as while(1){... if(i>10) break; } to see equivalence. Inserting a condition for(; i <= 10; ) would also work and avoids the explicit break.

Why Other Options Are Wrong:Claims that a condition is required are incorrect; the C standard allows empty control expressions. Replacing with while is optional, not required. Dropping semicolons would change syntax and be invalid.

Common Pitfalls:Assuming that an empty condition is illegal; miscounting the printed range and thinking 11 prints (it does not).

Final Answer:No error

More Questions from Control Instructions

Discussion & Comments

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