Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Execution of printf With ++ Operators in C

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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.

This article is contributed by Spoorthi Aman. 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. 

My Personal Notes arrow_drop_up
Last Updated : 25 Nov, 2021
Like Article
Save Article
Similar Reads