0

What is the effect if i use postfix for updating in loop statement compared to prefix? Is there any difference?

for example, for(i=0 ; i <=20 ; i++) for (i=0 ; i<=20 ; ++i ) is there any difference?

10th May 2018, 10:56 AM
Hyeong Hyuga
Hyeong Hyuga - avatar
2 Respostas
+ 1
There is a difference, but for primitive types ( like int ) it does not matter as it gets optimized. But you should avoid postfix because it creates a temp variable so it has to do a copy, for primitive types this is cheap but if you had your own types where copying is expensive this would be slow. Prefix does not need a temp variable so it avoids the unnecessary copy. Sure you could use i++ with primitive types and ++i on your own types. But why not just do it the right way and use ++i in both occasions. :) Here, read this: https://fairwaytech.com/2012/03/prefix-vs-postfix-increment-and-decrement-operators-in-c/
10th May 2018, 11:25 AM
Dennis
Dennis - avatar
0
nope, both are same, as there is no assignment
10th May 2018, 10:58 AM
‎ ‏‏‎Anonymous Guy