+ 1

Why does this code give the input "10"?

#include <iostream> using namespace std; int main() { int a, b; a=4; b=a + ++a; cout<<b; return 0; }

12th Oct 2018, 11:09 PM
Sławomir Durawa
Sławomir Durawa - avatar
2 ответов
+ 3
a + ++a is equal to a + (a=1+a). since a was incremented, that means its new value is 5. so 5+5. it takes the incremented value as new value during the operation because we put the plus sign(increment operator) before the number.
12th Oct 2018, 11:19 PM
Kuyondo
Kuyondo - avatar
+ 1
He's right, the output should be 10 because a in this case was changed during the operation to 5 with the ++a. The answer would have been 9 if b was presented as b=a+a++; because the entire line is calculated first in c++ unlike java https://code.sololearn.com/cDOlE0rgTSPf/?ref=app
12th Oct 2018, 11:40 PM
Evan Martine