[Solved] ‘In any case, follow the guideline “prefer ++i over i++” and you won’t go wrong.’ What is the reason behind this in C?


In the case of

for (i=start; i<end; i++)

vs

for (i=start; i<end; ++i)

their meanings are completely identical, because the value of the expressions i++ and ++i are not used. (They are evaluated for side effects only.) Any compiler which produces different code for the two is pathologically bad and should be chucked in the garbage. Here, use whichever form you prefer, but i++ is idiomatic among C programmers.

In other contexts, use the form that yields the value you want. If you want the value from before the increment, use i++. This makes sense for things like:

index = count++;

or

array[count++] = val;

where the old value of count becomes the index of a new slot you’re going to store something in.

On the other hand, if you want the value after increment, use ++i.

Note that for integer types, the following are all completely equivalent:

  • i += 1
  • ++i
  • i++ + 1

and likewise the following are equivalent:

  • (i += 1) - 1
  • i++
  • ++i - 1

For floating point and pointers it’s more complicated.

As far as any objective reasons are concerned, the advice you found is just nonsense. If on the other hand you find ++i easier to reason about, then feel free to take the advice, but this is going to depend entirely on the individual and what you’re used to.

2

solved ‘In any case, follow the guideline “prefer ++i over i++” and you won’t go wrong.’ What is the reason behind this in C?