+ 3
How come this code generates the output of 11?
INT I=4; I=++I+I++; cout<<I;
8 Answers
+ 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
+ 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?
+ 4
@Corsair Alex In c++, pre-increment takes precedence over addition. Post-increment comes last.
+ 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.
+ 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.
+ 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.
+ 1
thanks guys especially for the ones who split the expression and explained
+ 1
but then ... why when I did :
int b=1;
b=b++;
cout<<b;
I obtained 1 ? :/