+ 11

x++ and ++x in for loop

Does using ++x instead of x++ make any difference in a for loop like for example: for(int x = 0; x < 10; ++x) { if ( x % 3 == 0) cout << x << endl; }

13th Dec 2016, 9:10 AM
Yousousen
Yousousen - avatar
5 ответов
+ 6
Nope, but ++x can be ever so slightly faster.
13th Dec 2016, 9:13 AM
Jafca
Jafca - avatar
+ 6
@Jafca: Is it faster because the resulting code is "add 1 to...x" (linear discovery) vs. "load x. Now what? add 1 to it." (decision tree) ?
13th Dec 2016, 9:43 AM
Kirk Schafer
Kirk Schafer - avatar
+ 2
You cannot see the difference, at all. It's a funny question for interview but in real life it's not working) If there gonna be a big really big number instead of 10, it will be hard to find the difference even with a chronometer. So... never mind
17th Mar 2017, 11:15 AM
Art Stesh
Art Stesh - avatar
+ 1
for ++x it increments the value of x before assigning it while x++ assigns first then increments the value. eg int x=9; int y=++x; int j=x++; after executing the code the value of y is 10 while that of j is 9. the same works for the decrementor (--)
19th Mar 2017, 4:32 PM
Josh Cardif
Josh Cardif - avatar
0
the difference comes down to which to use best for your situation.
3rd Apr 2017, 6:04 PM
milk way
milk way - avatar