+ 2

Please explain the output of following code?

#include <iostream> using namespace std; int main() { int i =3; i=++i+i++; cout <<i; return 0; } #Output is 9 thanks everyone for answering but when I am replacing "i" with "a" then also I am getting 9 as output... #include <iostream> using namespace std; int main() { int i,a=3; i=++a+a++; cout <<i; return 0; } #output is 9 here also please someone explain it...

7th Feb 2018, 8:17 AM
Rishabh Rai
Rishabh Rai - avatar
3 Respuestas
+ 18
well generally when increment & decrement are applied on the same line on the same variable it depends on compiler what it will do first.... In this scenario.... the preincrement is applied 1st by compiler and operation is caried out then the the result of the operation is incremented on the next line i=3 i=++i+i++ //here i= (++i+i)++ (4+4)++ so result will become 9
7th Feb 2018, 8:54 AM
🌛DT🌜
🌛DT🌜 - avatar
+ 14
if its in java , then output will be 8
7th Feb 2018, 8:26 AM
Gaurav Agrawal
Gaurav Agrawal - avatar
+ 2
Do not worry. These are just education and challenge questions. I haven't s seen them in real code because this is really confusing. i = //assign a value to i (++1) //increment before executing statement : increment i with 1 + // add left and right (i++) //increment after executing statement : increment i with 1 i was 3 after ++i than i is equal to 4 4+4 equals 8 i++ increment after statement make i equals 9 result is 9
7th Feb 2018, 9:11 AM
sneeze
sneeze - avatar