Use of pre/post Increment operator in expression



In this example we will be learning very typical example of C Program where we will be using pre increment and post increment operators in same expression.

Re-commanded Reading : Increment Operator in C | Decrements Operator in C

Postfix and Prefix Expression in Same Statement

#include<stdio.h>
#include<conio.h>

void main() {
   int i = 0, j = 0;
   j = i++ + ++i;
   printf("%d\n", i);
   printf("%d\n", j);
}

Output :

2
2

Explanation of Program

A picture worth 100 lines of text. Consider the below program picture which explains the above program.

j = i++ + ++i;

Above line of code have total four operators –

  1. Assignment Operator
  2. Post Increment Operator
  3. Pre Increment Operator
  4. Arithmetic Operator

Now we need to arrange all the operators in the decreasing order of the Precedence –

OperatorPrecedence Rank
Pre Increment1
Post Increment2
Arithmetic Operator3
Assignment Operator4

Now we have arranged all the operators in the decreasing order of the precedence. (Operator Precedence and Associativity Document)

Execution flow

  1. In the first step pre-increment operator gets an opportunity for execution. It will increment the value of variable
  2. In the second step post increment operator will be executed. It does not increment the actual value of variable but mark it as pending execution.
  3. Here pre-increment operation uses new Value of ‘i’ so [ i = 1 ].
  4. This ‘i = 1’ is used for Post Increment Operation which uses Old Value i.e [i = 1] .
  5. Both ‘1’s are added and value 2 is assigned to ‘j’.

Summary :

Step 1 : j = i++ + 1;
Step 2 : j = 1 + 1; (post-increment pending on i)
Step 3 : j = 2; (Addition)
Step 4 : j = 2; (Assignment)
Step 5 : Pending increment on i will be executed