Difficulty: Medium
Correct Answer: The for loop would get executed infinite times
Explanation:
Introduction / Context:
This problem probes understanding of C for loop semantics, side effects in the test expression, and I/O function return values. It also hints at format-specifier correctness and how undefined behavior may arise.
Given Data / Assumptions:
Concept / Approach:
scanf returns the number of successfully matched and assigned items. With the format "%s", a non-empty token read returns 1, which is nonzero and therefore true. Hence, as long as input provides tokens and no error/EOF occurs, the loop condition remains true and iterations continue.
Step-by-Step Solution:
The initialization field is empty, so no init step.Condition calls scanf; returns 1 on each successful string read → true.Since the body is empty, control immediately executes the third expression, printing i.With ongoing input, the loop keeps iterating without an intrinsic bound → effectively infinite.
Verification / Alternative check:
Practically, the loop terminates only if scanf returns 0 or EOF (e.g., Ctrl+Z/Ctrl+D) or an I/O error; otherwise it continues.
Why Other Options Are Wrong:
A/B/C give fixed counts unrelated to input-driven behavior. E is more precise in a strict sense, but the intended conceptual takeaway is “no built-in termination,” i.e., effectively infinite for continuous input.
Common Pitfalls:
Using "%s" with an int* is a format mismatch and causes undefined behavior. In real code, use a char buffer for "%s" or change the format to "%d".
Final Answer:
The for loop would get executed infinite times
Discussion & Comments