Pre and post increment | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Pre and post increment

does anybody know the logic behind ++x + ++x + ++x. and statements like that where preincremet is used more than once. its a bit counterintuitive!

6th Jan 2017, 3:00 PM
Shoaib Azam
Shoaib Azam - avatar
4 Answers
+ 3
x++ simply means (x += 1) or (x = x + 1) which are the same thing. So say: x = 0 x++ + 2 means increment x by 1 AFTER evaluating the statement\line\expression (i.e. execute the statement (x+2) THEN increase x by 1 which would = 2). ++x + 2 means increment x by 1 BEFORE evaluating the statement\line\expression (i.e. increase x by 1 THEN execute the statement (x+2) which would = 3). The location of (++) is kind of meant to imply before (++x) and after (x++). Hope this helps.
6th Jan 2017, 3:50 PM
Bou Hani
Bou Hani - avatar
+ 3
I think different compilers might give different results depending on how they implement their pre-post-in-fix operations. I've tested this on - MS Visual Studio C++ compiler; the answer is: 18 - Playground here on sololearn; the answer is: 16 (most likely gcc) - Linux using gcc 4.8.5 which also gives: 16 - Chrome console (JS) which gives: 15 Anyways, here is a quick general explanation -- as I understand it: - Based on your example, we assume x = 3 - MS VS seems to hold the whole expression's evaluation until the last increment of x which is the third one in our example. By the time it increment the last one, x will equal 6 because it's been incremented 3 times. So essentially, the final execution is for the whole expression which will give: (x + x + x) = (6 + 6 + 6) = 18 replacing all x's by the last value we got from the last increment. - gcc seems to evaluate them in pairs. So it first evaluates (++x + ++x) which will have the same logic as above. By the time we reach the 2nd ++x, x will equal 5 in our example (a total of two increments). So (5 + 5) = 10. Then, (10 + ++x) = (10 + 6) = 16. And if you have 4 terms, then it would evaluate the 2nd pair of (++x)'s on its own then add it to the previous result ... and so on. - Chrome JS seems to evaluate each term on its own and immediately replace the result of x instead of referencing x at the final evaluation. So (++x + ++x + ++x) = (4 + ++x + ++x) = (4 + 5 + ++x) = (4 + 5 + 6) = 15. I'm not a 100% sure that this is what's exactly going on, but that's how I understand it at the moment given the limited and quick tests.
7th Jan 2017, 7:12 AM
Bou Hani
Bou Hani - avatar
+ 1
thank you indeed
7th Jan 2017, 7:17 AM
Shoaib Azam
Shoaib Azam - avatar
0
if x=3; cout<< ++x + ++x + ++x; i was expecting an output 15!!!
7th Jan 2017, 6:03 AM
Shoaib Azam
Shoaib Azam - avatar