Difference between Pre & Post Increment/Decrement
Consider the following code snippet:-
int A = 0;
At the very first line, we have used the Arithmetic Assignment operator, = to assign the value of 0 to A. In the proceeding lines we have used both Pre & Post increment. At line 2 int B = A++; the operation being post increment, the value of A i.e 0 is assigned to B followed by the increment of A’s value. At line 3 int C = ++A; the current value of A, i.e. 1 is incremented by 1 following which the new value of A is assigned to C. Therefore, the value of A = 2, B = 0 and C = 2.
What will be the output of the following code?
int A = 5;
At line, 1, A gets initialized to 5. The next line is a bit tricky. Here, The RHS should be evaluated like 5 + 4 because A++ is post increment and this operation should occur after the line of statement. But, this is not the case, instead it takes place in the same line but after the evaluation of the sub-expression (A++). Hence, the expression will be evaluated as 5 + 5 and the output will be 10.