Monday, July 8, 2013

Difference between Pre-Increment and Post-Increment Operators

As we already know that Unary Operators are of two types, Increment and Decrement Operators. Increment Operator is used to increment the value by one and the Decrement Operator is used to decrement the value by 1.

Again these Increment and Decrement Operators are divided into two types, pre and post. There is a lot of difference between in this pre and post. ++x comes under Pre-Increment Operator and x++ comes under Post-Increment Operator.

We can understand this difference with an example program. Consider the following program.



  1. #include<stdio.h>
  2. main()
  3. {
  4. int a,b;
  5. a=b=5;
  6. printf(" Intially the values of a and b are %d and %d \n", a,b);
  7. printf(" pre-increment a - %d  and post-increment b - %d", ++a, b++);
  8. printf(" pre-decrement a - %d and post -decrement b - %d, --a, b--);
  9. return 0;
  10. }
The output of the above program will be
Initially the values of a and b are 5 and 5.
pre-increment a - 6 and post-increment b - 5
pre-decrement a - 5 and post -decrement b - 6

 You might be confusing about the result. I will give you a analysis of the result.

Initially the values of a and b are 5 each. When we perform pre-increment on a, before using a, we are incrementing the value of a and hence the output is printed as 6 and when we post-increment b, we use the value of b first and then increment it. So the output is 5 and after printing, it turns to be 6.

By the second statement, we have values of a and b as 6 and 6.

When we perform pre-decrement on a, we decrement the value of a by one and print it, so, the output is 5 and for b, as we have post-decrement, we print out the value 6 and then it gets decremented.

In most of the competitive examinations, we can see the questions on Increment and Decrement Operators as they are bit confusing. We should be careful in understanding the expressions and analyze the problem.

One such a problem is mentioned here. Follow this link to understand more on Increment Operators