Wednesday, October 23, 2013

Pre increment and post increment operator


The pre increment and post increment operators work identical if they are used independently.
Look at the following code:

Program 10:  
#include <stdio.h>
#include <conio.h>
void main()
{
    int i=2,j=2;
    clrscr();
    ++j;
    i++;
    printf("The value of i=%d”,i);
    printf("\nThe value of j=%d”,j);
   getch();
}
Output:
#-------------------------------------------------------------------------------#
The value of i=3
The value of j=3
#-------------------------------------------------------------------------------#

Here, in the statement ++j the ++ before the variable j is called the pre increment operator whereas the ++ after the variable I is called post increment operator. Their real behavior can be studied when they are used in expressions. The following program demonstrates the difference between these two.

Program 11:  
#include <stdio.h>
#include <conio.h>
void main()
{
    int i=2,j=2,a,b;
    clrscr();
    a=++j;
    b=i++;
    printf("a=%d  and b=%d”,a,b);
    printf("\ni=%d j=%d”,I,j);
   getch();
}
Output:
#-------------------------------------------------------------------------------#
a=3 and b=2
i=3 j=3
#-------------------------------------------------------------------------------#

Here, the value of a is 3 whereas the value of b is 2 because pre increment operator first increments the value of the operand it precedes and then assigns the value of the operand to the variable on the left hand side. So, in the statement a=++j, first the value of the variable j is incremented by 1 and then the value (i.e. 3) is assigned on the variable on the left hand side i.e. a. In the statement b=t++, first the value of i is assigned to the variable on the left hand side i.e. b and then incremented the value of i i.e. 2. So, the statement
          b=i++; is same as
         b=i;
         i++;
Whereas the statement a=++j is similar to
          j++;
         a=j;

Pre decrement and post decrement operator:

The working principal of the pre decrement and the post decrement operator is similar as that of pre increment and post increment operators except that they decrement the value of the variable.

No comments:

Post a Comment