-4
int i;
for(i = n; i --> 0;)

and

for(i = n; i > 0; --i)

They are producing different results.

mch
  • 9,424
  • 2
  • 28
  • 42

2 Answers2

4

As for the first one, i is decremented before the loop body is executed. The second one decrements i after the loop body is executed.

Jeonghyeon Lee
  • 244
  • 1
  • 7
  • I find your answer incomplete as it does not discuss the behaviour (value) of `i` in the comparisson. – Paul Ogilvie Jan 25 '17 at 10:32
  • @PaulOgilvie well, the value of i in the comparison is the same for both cases. The postfix decrement means the COMPARISON is with the value before decrementing - but because the decrement is now at the head of the loop, the value of `i` in the loop is different. – Roddy Jan 25 '17 at 10:36
  • @PaulOgilvie The comparison is the same, both loops iterate _n_ times with the same values. The only difference is the value of `i` inside the loop. – rom1v Jan 25 '17 at 10:37
2

The difference is the step in which i is actually decremented, which affects the values of i seen inside the loop body.

The second traditional version decrements i after the loop body is executed, and before the condition is checked again. Thus i reaches 0 after the loop body is executed for i == 1. The condition is checked again and after the loop i is 0.

The first version decrements i before the loop body is executed, as part of the condition being checked. Here the loop body runs the first time with i == n - 1 and the last time with i == 0. Then i is decremented and its previous value compared against 0. The loop exits and i is -1 after it.

In the traditional version, the loop body always sees the same value against which the conditional part was checked.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458