Post increment operator in expression



We have already studied the pre and post increment operators in c programming. In this tutorial we will be learning different examples of post increment operator.

Examples of post increment operator in expression

Before going through the different examples we can consider below values as initial values for each program explained below -

int i=0,j=0;
int k = 0;
int temp=3;

Depending upon these initial values try to grasp the below programs -

1.Post Increment Verity No 1

int main() {
   int num = 0, result = 0, i = 0;
   for (i = 0; i < 5; i++) {
      result = num++;
      printf("%d", result);
   }
   return 0;
}

Output : [ 0 1 2 3 4 ]

Consider the above program where we have used following statement -

result = num++;

num++ is a post increment which means we are firstly assigning the old value of variable ‘num’ to ‘result’. After assigning the older value of ‘result’ we will be increment value of ‘num’

2.Post Increment Verity No 2

int main() {
   int num = 0, i = 0;
   for (i = 0; i < 5; i++) {
      printf("%d", num++);
   }
   return 0;
}

Output : [ 0 1 2 3 4 ]

Inside printf function we have used post increment operator. It will print the value of variable first and then it will increment the value of variable after execution of printf statement.

3.Post Increment Verity No 3

for(k=0;k<5;k++)
  {
  j = i++ + temp;
  printf("%d",j);
  }

Firstly old value of ‘i’ is added with temp and result of addition is assigned to ‘j’. After addition value of ‘i’ will be incremented

4.Post Increment Verity No 4

for(k=0;k<5;k++)
  {
  j = i++ < temp;
  printf("%d\n",j);
  }

Re-commanded Article : Conditional Operator in Expression

Firstly old value of ‘i’ is compared with ‘temp’ . Then result is assigned to j, and new value is used in second iteration.

5.Post Increment Verity No 5

for(k=0;k<5;k++)
  {
  j = i++;
  printf("%d",i);
  }
  • Old value of ‘i gets reflected only within same expression
  • In the above snippet Old value is assigned to ‘j’ . but in the next statement always ‘new value’ is used.
  • So while printing i Output will be = [1 2 3 4 5].

6.Post Increment Verity No 6

for(k=0;k<5;k++)
  {
  i = i++;
  printf("%d",i);
  }
  • Old value of ‘i is assigned to ‘i’ itself.
  • And again value is incremented after assigning.
  • So while printing i Output will be = [1 2 3 4 5].
  • But this Type is not supported by many compiles .

Note :

  1. Same things happens while using Post-Decrement.
  2. Post Increment is Unary Operator.
  3. Post-Increment Operator has Highest Priority