Open In App
Related Articles

Execution of printf With ++ Operators in C

Improve Article
Improve
Save Article
Save
Like Article
Like

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.

If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 25 Nov, 2021
Like Article
Save Article
Previous
Next
Similar Reads