Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
486 views
in Technique[技术] by (71.8m points)

post increment - 'In any case, follow the guideline "prefer ++i over i++" and you won't go wrong.' What is the reason behind this in C?

I had come across this answer to this question. In one of the line, the author mention's:

In any case, follow the guideline "prefer ++i over i++" and you won't go wrong.

I know that ++i is slightly faster than i++, but thought that there is no reason for them to go wrong. I searched for a while, and the closest I could get to was this. It explained clearly that why is it preferred to use ++i, but not still how could you go wrong using i++.

So can anyone tell me how can i++ go wrong?

NOTE: My question isn't a dupe, as I am not asking about the performance. I have already seen that question. I am asking how can i++ be wrong as mentioned in the answer I have mentioned above.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...