C multiple increment operators inside printf
We have already learnt different ways of using increment operators in c programming. In this tutorial we will study the impact of using multiple increment / decrement operators in printf.
Re-commanded Article : Use of Pre/Post increment operator in same expression
Multiple increment operators inside printf
#include<stdio.h> void main() { int i = 1; printf("%d %d %d", i, ++i, i++); }
Output :
3 3 1
Pictorial representation
Explanation of program
I am sure you will get confused after viewing the above image and output of program.
- Whenever more than one format specifiers (i.e %d) are directly or indirectly related with same variable (i,i++,++i) then we need to evaluate each individual expression from right to left.
- As shown in the above image evaluation sequence of expressions written inside printf will be - i++,++i,i
- After execution we need to replace the output of expression at appropriate place
No | Step | Explanation |
---|---|---|
1 | Evaluate i++ | At the time of execution we will be using older value of i = 1 |
2 | Evaluate ++i | At the time of execution we will be increment value already modified after step 1 i.e i = 3 |
2 | Evaluate i | At the time of execution we will be using value of i modified in step 2 |
Below is programmatic representation of intermediate steps -
After Step 1 : printf("%d %d %d",i,++i,1); After Step 2 : printf("%d %d %d",i,3,1); After Step 3 : printf("%d %d %d",3,3,1); After Step 4 : Output displayed - 3,3,1
After solving expressions printing sequence will : i, ++i, i++
Examples of typical expresssions
No | Example |
---|---|
1 | How to use pre-post increment operators inside same expression ? |
2 | How to use post increment statement inside expression ? |
3 | How to use conditional operators in expression ? |