+ 1
Why this code gives 7 as output?
int i = 2; i = ++i + i++ ; cout << i;
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.
+ 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.....
+ 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.
+ 2
in javascript output 6
i=2;
i=++i+i++;
alert(i);
0
isnt an order fixed, ie, rtl or ltr? and what is associativity of post and pre increment operators? @marcram
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.