For-loop with scanf in the test expression: how many times does this loop execute (conceptually)? #include<stdio.h> int main() { int i = 5; for ( ; scanf("%s", &i); printf("%d ", i) ); return 0; }

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:

  • The loop header uses scanf("%s", &i) as the test (condition) expression.
  • The third expression prints the current i: printf("%d", i).
  • No explicit loop body; only semi-colon after the header.
  • Conceptual answer expected for typical interactive input streams.


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

More Questions from Declarations and Initializations

Discussion & Comments

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