Originally posted by Sujittt Tripathyrr:
You are confusing me , after incrementing the RHS i value you are assigning to LHS i or before incrementing you are assigning.
Lets talk about increment operators in a bit detail, which will hopefully help resolve your confusion.
The expressions ++i and i++ both have increment operators.
Both of them return a value and also have a side effect.
For both of them, the side effect is that the value is incremented by 1.
So now where is the difference?
The preincrement operator, as the
word indicates, first does the side effect and then returns the value. So when we say
j = ++i;
Here the value of 'i' gets incremented first. And then the result is assigned to the variable on the left side of the assignment. Note that what is on the left side hardly matters.
int i = 20;
int j = ++i; // firt increment i. So now i becomes 21. Now assign this value to j.
i = ++i; // firt increment i. So now i becomes 21. Now assign this value to i.
note that in the second example, it doesnot matter what variable in on Left side of the assignment (provided types etc are correct.)
As an aside , observe that
i = ++i;
is same as
++i;
Thats about the pre-increment operator.Now lets see the post increment operator
int i = 20;
int j = i++;
As the name indicates, the "side effect" occurs AFTER the expression on the right side of the assignment operator is evaluated, but BEFORE the actual assignment takes place. So, in the above example the expression on the right side of the assignment will be evaluated to get the value of i, which will be 20. Thus note that the right-side expression returns the value 20, which will be assigned to the variable on the left side of the assignment (j in this case.). But before the actual assignment takes place, the side effect causes i to get the value 21. Note that this side effect only changes the value of i, it has nothing to do with the value generated by evaluating the right-hand-side expression. (It will be easy to understand this if you consider
a) evaluating right-side-expression
and
b) side effect
as two independent tasks.
So finally when we say
int i = 20;
i = i++;
what happens?
a) Right side is evaluated to get the value 20
b) Due to the side effect (of right-side expression) the variable i gets the value 21
c) The assignment expression is evaluated. What value is assigned to i on left-side of the assignment? not the value of i after the side effect, but the value of i that was present after right-side expression was evaluated. Which means 20.
Thus, i gets 20.
Thus, also note that
i = i++;
doesnot change the value which was originally present in i.
It will also be easy to understand if you see the expression
i = i++;
as :
i) evaluate Right-side and store it in a temporary variable, temp.
ii) carry out the side effect, which means increment i
iii) carry out the assignment, which means assign the value temp to the variable on left side of the assignment, namely i.