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

空扰寡人 提交于 2019-12-13 09:35:18

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/35643963/in-any-case-follow-the-guideline-prefer-i-over-i-and-you-wont-go-wrong

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!