Tuesday, March 10, 2009

Difference between Pre & Post Increment/Decrement

Difference between Pre & Post Increment/Decrement
Consider the following code snippet:-

1
2
3
int A = 0;

int B = A++;
int C = ++A;

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.

Maxotek Blog » C# Tutorial


What will be the output of the following code?

1
2
3
int A = 5;

int B = (A++) + (--A);

Console.WriteLine("Value of B = {0}", B);

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.

No comments: