Open In App

Execution of printf With ++ Operators in C

Last Updated : 25 Nov, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Consider the following statement in C and predict its output.

printf("%d %d %d", i, ++i, i++);

This statement invokes undefined behavior by referencing both ‘i’ and ‘i++’ in the argument list. It is not defined in which order the arguments are evaluated. Different compilers may choose different orders. A single compiler can also choose different orders at different times.

For example, below three printf() statements may also cause undefined behavior:

C




// C Program to demonstrate the three printf() statements
// that cause undefined behavior
#include <stdio.h>
  
// Driver Code
int main()
{
    volatile int a = 10;
    printf("%d %d\n", a, a++);
  
    a = 10;
    printf("%d %d\n", a++, a);
  
    a = 10;
    printf("%d %d %d\n", a, a++, ++a);
    return 0;
}


Output

11 10
10 10
12 11 11

Explanation: Usually, the compilers read parameters of printf() from right to left. So, ‘a++’  will be executed first as it is the last parameter of the first printf() statement. It will print 10. Although, now the value has been increased by 1, so the second last argument, i.e., will print 11. Similarly, the other statements will also get executed.

Note: In pre-increment, i.e., ++a, it will increase the value by 1 before printing, and in post-increment, i.e., a++, it prints the value at first, and then the value is incremented by 1.

Therefore, it is not recommended not to do two or more than two pre or post-increment operators in the same statement. This means that there’s absolutely no temporal ordering in this process. The arguments can be evaluated in any order, and the process of their evaluation can be intertwined in any way.

 


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads