KatInterview

Counting Iterations of a C Loop With an Assignment Condition

Math & Bit ManipulationModel answer
EasyModel answerMath & Bit Manipulationc-languagecontrol-flowoperators

Last updated

Work out how many times a C for-loop body runs when its condition is an assignment expression rather than a comparison, and explain the final variable values.

Two variables m and n are declared as int. Look at this fragment of standard C:

int m, n;
for (m = 0, n = -1; n = 0; m++, n++)
    n++;

Assume ordinary C semantics, so = is assignment and == is comparison.

Questions

  1. How many times does the body statement n++ run?
    • A. Zero times
    • B. Exactly once
    • C. Forever (infinite loop)
    • D. The program fails with a runtime error
  2. What are the values of m and n once the loop statement has finished?
  3. Would the iteration count or the final values change if the condition were n == 0? What if it were n = 1?

Give your answer with a short step-by-step trace and justify why each rejected option is wrong.

Hints

Hint 1

An assignment expression in C is not just an action: it also produces a value. Ask yourself what value `n = 0` produces.

Hint 2

Recall the order in which a `for` loop executes its three clauses, and when the condition is first examined relative to the body.

Hint 3

A compiler warning about assignment used as a truth value is a compile-time diagnostic. Decide whether the code is actually legal and well defined before considering a runtime failure.