+ 8
Usage of ++i and i++
I know the difference between i++ and ++i. But I don't know how exactly they are evaluated. For example, ++i += i i = ++i + i++ are two expressions using i++ and ++i. I want to know how these expressions are evaluated. Awaiting reply.
6 odpowiedzi
+ 6
In addition context, both will have no difference.
But in terms of function, yes they will have difference.
i++ is postfix while ++i is prefix.
I will show you an example first :
int x = 1;
int y = 1;
int ResultX = x++;//Postfix
int ResultY = ++y; //Prefix
cout << ResultX <<endl;
cout << ResultY <<endl;
/*outputs a 1, then a 2.*/
cout << x << endl;
cout<< y << endl;
/*outputs a 2, then a 2 again.*/
From that example, you can see that ResultX became x ,while x became (x+1). Which means that postfix forms processes the code first before doing addition/subtraction of values.
And
ResultY became (y+1) and y also became (y+1). Which shows that prefix form does addition/subtraction of value first before processing the code.
-------------------
Now to answer your main question.
Lets treat 'i' as 1 in both cases'
Case 1 :
int i = 1;
++i += i;
'i' in that case will be four. The reason is because remember that how for prefix addition comes first? So 'i' would become 2 first. Now it will read it as " i += i " and 'i' just became 2, so to summarize it, the expression became " i = 2+2 ".
Case 2:
int i = 1;
i = ++i + i++
'i' in that case will be five. The reason for that is because again, we have a prefix, so 'i' will be added by one first, so 'i' will become 2. So now it reads it as " i = i + i++ ". So the postfix is tricky, but always remember : postfix ALWAYS do addition/subtraction at the last minute. So do your addition first , 2+2 = 4. Now 'i' became 4. Lastly, the postfix addition, and there you have it... 'i' became 5 after the postfix addition.
+ 4
I edited my previous answer to answer your main question about evaluating the two equations. Check it around the bottom of my answer.
It should be separated with a long dash line.
+ 1
awesome @K2 Shape @OP
i have a related question.
in
i = ++i + ++i
which one gets evaluated first ? i mean is it from left to right or from right to left?
+ 1
++I means first +1 is added then used
whereas I++ means I is first used then +1 is added
0
well not sure if im understanding the question but from what i understand i++ evaluates the increment after and ++i evaluates the increment before.
so if :
x=5
y= ++x ---> y = x+1 and x= x+1
then y= 6 and x = 6
then if
y = x++ ----> y = x; x= x+1
so y= 5 and x = 6
dont know if that is clear
0
I did not get it