+ 3

How come this code generates the output of 11?

INT I=4; I=++I+I++; cout<<I;

31st Dec 2016, 12:46 PM
Shravan Kumar
Shravan Kumar - avatar
8 odpowiedzi
+ 5
Hi, Please refer to http://en.cppreference.com/w/cpp/language/operator_precedence for the precedence and associativity of C++ operators. Basically from your expression let, I = 4, x = ++I (4+1 = 5) = 5, y = I++ (5+1 = 6) = 6, I = (x) + (y) = 5 + 6 = 11
31st Dec 2016, 12:57 PM
Alex Soh Chye Wat
Alex Soh Chye Wat - avatar
+ 4
@Ken Kaneki and @ATR110, Pardon me if i'm wrong but isn't the operator's precedence for post-increment and pre-increment is higher than addition and subtraction?
31st Dec 2016, 1:08 PM
Alex Soh Chye Wat
Alex Soh Chye Wat - avatar
+ 4
@Corsair Alex In c++, pre-increment takes precedence over addition. Post-increment comes last.
31st Dec 2016, 1:13 PM
Dao
Dao - avatar
+ 4
@Corsair Alex Pre-increment have preference over operators, post-increment not.But in this case the result is the same if you ignore the preference.
31st Dec 2016, 1:14 PM
atralvarez
atralvarez - avatar
+ 3
l initially is 4, the first increment operator makes it 5, so the second line becomes 5 + 5, and there's another increment operator at the end, which adds 1 to 5 + 5. 11.
31st Dec 2016, 12:59 PM
Dao
Dao - avatar
+ 2
You can split the code by this way: 1) Start -> I = 4 2) Operation: (a + b) a) ++I -> I = 5 b) I++ -> 5 (At this moment I equals 5, only catch the current value of I, then it will increment in one more (++). 3) a = 5 b = 5 I = 5+5 = 10 But you have a ++, so it will be 11 when you print it.
31st Dec 2016, 12:58 PM
atralvarez
atralvarez - avatar
+ 1
thanks guys especially for the ones who split the expression and explained
31st Dec 2016, 1:24 PM
Shravan Kumar
Shravan Kumar - avatar
+ 1
but then ... why when I did : int b=1; b=b++; cout<<b; I obtained 1 ? :/
31st Dec 2016, 2:32 PM
Baptiste E. Prunier
Baptiste E. Prunier - avatar