+ 1

Why this code gives 7 as output?

int i = 2; i = ++i + i++ ; cout << i;

26th Oct 2016, 5:57 PM
Manul Goyal
Manul Goyal - avatar
6 ответов
+ 5
My guess: i = ++i + i++; (i is 2) i = 3 + i++; (i is 3) i = 3 + 3 (i is 3) i is 6, and is then incremented by i++ to 7. But really, you won't find this kind of stuff in real life, and I'm not even sure the implementation is standardized and not compiler-dependant.
26th Oct 2016, 6:06 PM
Zen
Zen - avatar
+ 3
according to your q. i=++i + i++; the compiler firstly preincrements i after seeing ++i now i becomes 3 and the line as follows: i=3+3; now the post increment you used makes compiler to increment the value by 1 after executing above line , hence i becomes 7 is show on screen.... this happens because the compiler reads a whole line at once.....
28th Oct 2016, 1:35 AM
Jatin
+ 2
As @Zen says, using our logic (from left to right) the result is 7. But if the compiler uses another order (from right to left) the result is 6. i = ++i + i++ --> i = i++ + ++i i = 2++ + ++i i = 2 + 4 = 6 it depends on the compiler. That's why it's better not to use such these expressions.
26th Oct 2016, 7:08 PM
marcram
+ 2
in javascript output 6 i=2; i=++i+i++; alert(i);
20th Feb 2017, 6:12 AM
Didi Georgel Danaila
Didi Georgel Danaila - avatar
0
isnt an order fixed, ie, rtl or ltr? and what is associativity of post and pre increment operators? @marcram
2nd Nov 2016, 11:40 AM
Manul Goyal
Manul Goyal - avatar
0
@Manul, as I understand it, the way it works depends only to the rules of every compiler. Normally it works like @Zen says, but there is the possibility that the software you use uses RtL order instead of LtR. So, as a logic exercise, @Zen's answer is the good one; otherwise, in a real practical code, it's better not to use more than one increment in the same operation.
2nd Nov 2016, 1:32 PM
marcram