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 this question. in 1 of line, author mention's:

in case, follow guideline "prefer ++i on i++" , won't go wrong.

i know ++i faster i++, thought there no reason them go wrong. searched while, , closest this. explained why preferred use ++i, not still how go wrong using i++.

so can tell me how can i++ go wrong?

note: question isn't dupe, not asking performance. have seen question. asking how can i++ wrong mentioned in answer have mentioned above.

in case of

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

vs

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

their meanings completely identical, because value of expressions i++ , ++i not used. (they evaluated side effects only.) compiler produces different code 2 pathologically bad , should chucked in garbage. here, use whichever form prefer, i++ idiomatic among c programmers.

in other contexts, use form yields value want. if want value before increment, use i++. makes sense things like:

index = count++; 

or

array[count++] = val; 

where old value of count becomes index of new slot you're going store in.

on other hand, if want value after increment, use ++i.

note integer types, following equivalent:

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

and likewise following equivalent:

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

for floating point , pointers it's more complicated.

as far objective reasons concerned, advice found nonsense. if on other hand find ++i easier reason about, feel free take advice, going depend entirely on individual , you're used to.


Comments

Popular posts from this blog

gridview - Yii2 DataPorivider $totalSum for a column -

java - Suppress Jboss version details from HTTP error response -

Sass watch command compiles .scss files before full sftp upload -