Output Please Explain it | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

Output Please Explain it

int i=3; i=++i+i++; cout<<i; outputs 9 This question is in the challenges section. I got it wrong.😔😔😔 also from my knowledge the answer should be compiler dependent because different compilers interpret it in different ways as my brain's compiler interpreted output to be 8😀😀😀

25th Nov 2016, 4:24 PM
Megatron
Megatron - avatar
5 Answers
+ 3
I thought post increment operator uses value then increases it. Also I thought c++ compiler compiles left to right and not from right to left so first post increment evaluates and then pre increment. Feel free to correct me if I am wrong at any point.
25th Nov 2016, 4:36 PM
Megatron
Megatron - avatar
+ 2
i = ++i + i++; // i = 3 i = 4 + 4; // since its ++i, so its incremented to 4(Pre-increment). Now i is 8. cout << i; // It will print 9 because, compiler will do the post-increment which is there in previous statement. Which is not like i = 4 + 5, then there will not be any difference between pre and post increments. C++ evaluates from left to right, so first pre-increment will be done and use the value for calculation and store it to the left side variable. After that only post increment will be performed. Hope you are clear now....
25th Nov 2016, 7:08 PM
Venkatesh(Venki)
Venkatesh(Venki) - avatar
+ 2
No still not clear. according to what you wrote int i=3 i=i++; cout<<i; should output 4 but outputs 3.
26th Nov 2016, 1:31 AM
Megatron
Megatron - avatar
+ 1
I dont have confidence on what should be performed after ++i = 4. there are 2 ways: assignment i = 4+4 or post-increment i = 5. looks like both: assignment and increment. But it doesnt works for 10 + i++ when we get 13
25th Nov 2016, 9:02 PM
dzmitry
0
i=++i+i++; i=4+i++; //++i=4 and then i=4 i=4+5; //i++=5 and then i=5 i=9;
25th Nov 2016, 4:31 PM
Nguyễn Hoàng Long
Nguyễn Hoàng Long - avatar