Counting Iterations of a C Loop With an Assignment Condition
Math & Bit ManipulationModel answerLast 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
- 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
- What are the values of
mandnonce the loop statement has finished? - Would the iteration count or the final values change if the condition were
n == 0? What if it weren = 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.
Model answer
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Answer
A. The body runs zero times. After the loop statement, m == 0 and n == 0.
Key idea
In C, n = 0 is an expression, not a statement-only action. It does two things:
- It stores
0inn. - It yields the value that was stored, which is
0.
In a condition, the value 0 means false. So the condition is false the first time it is evaluated.
Trace
A for (init; cond; step) body behaves like:
init;
while (cond) {
body;
step;
}
| Step | Action | m | n | Note |
|---|---|---|---|---|
| 1 | m = 0, n = -1 (init) | 0 | -1 | Comma operator evaluates left to right with a sequence point between |
| 2 | n = 0 (cond) | 0 | 0 | Expression value is 0, so false |
| 3 | Loop exits | 0 | 0 | Neither body nor step ever runs |
The condition is tested before the first iteration, so the body and the m++, n++ step are skipped entirely. Note that n ends at 0, not -1, because the condition has a side effect even though no iteration happens.
Why the other options fail
- B (once): This reasoning fits a
do { } whileloop, where the body precedes the first test. Aforloop tests first. - C (infinite): This would happen with a nonzero assigned value such as
n = 1. Each check would resetnto 1 and the condition would stay true. Assigning0does the opposite. - D (runtime error): Nothing here is undefined behavior. Using an assignment as a condition is legal. Compilers with warnings enabled (for example
-Wall) report "assignment used as truth value", but that is a compile-time warning, not a runtime failure.
Variants (part 3)
| Condition | Body runs | Final m | Final n |
|---|---|---|---|
n = 0 | 0 | 0 | 0 |
n == 0 | 0 | 0 | -1 |
n = 1 | infinite | grows | never leaves the loop |
With n == 0, the first check compares -1 with 0, which is false, so the count is still zero but n stays -1. Both readings agree on the count and differ only in the final state. That is why tracing the actual side effects matters more than guessing "this is a typo, so the answer must differ".
For n = 1, the condition is always true. Each iteration also runs n++ in the body and n++ in the step, but the condition overwrites n with 1 before every check, so the loop never terminates (assuming m does not overflow; signed overflow in m++ would eventually be undefined behavior, which is another reason to avoid such code).
Complexity
One initialization and one condition check: O(1) time and O(1) space.
Related points worth mentioning
- Assignment value:
x = exprevaluates to the new value ofx. This is what makes idioms likewhile ((c = getchar()) != EOF)andif ((p = malloc(k)))work. Extra parentheses signal to readers and compilers that the assignment is intentional. - Comma operator vs. separator: In the init clause,
m = 0, n = -1uses the comma operator, which guarantees left-to-right evaluation. In the declarationint m, n;the comma is only a separator. - Defensive style: Writing constants on the left (
0 == n) turns an accidental=into a compile error. Enabling-Wall -Werrorachieves a similar effect with more readable code.
Simulation sketch
A small Python model of the same semantics, using the walrus operator to mimic an assignment inside the condition:
def simulate(init_m, init_n, assigned, max_iters=1000):
m, n = init_m, init_n
count = 0
while (n := assigned) != 0: # assign, then test the value
n += 1 # body
count += 1
m += 1 # step: m++, n++
n += 1
if count >= max_iters:
return None, m, n # treated as infinite
return count, m, n
print(simulate(0, -1, 0)) # (0, 0, 0)
print(simulate(0, -1, 1)) # (None, ...) infinite
Common mistakes
- Reading
n = 0as a comparison and concludingnstays-1. - Believing a
forbody always runs at least once. - Confusing a compiler warning with a runtime error.
- Forgetting that the condition's side effect still changes
neven with zero iterations.