Execution of printf with ++ operators

Consider below C++ program and predict its output.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


The above invokes undefined behaviour 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.

filter_none

edit
close

play_arrow

link
brightness_4
code

// All three printf() statements 
// in this cause undefined behavior
#include <stdio.h>
  
int main()
{
    volatile int a = 10;
    printf("\n %d %d", a, a++);
  
    a = 10;
    printf("\n %d %d", a++, a);
  
    a = 10;
    printf("\n %d %d %d ", a, a++, ++a);
    return 0;
}

chevron_right


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 contribute.geeksforgeeks.org or mail your article to contribute@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

Improved By : ArunSivaramakrishnanS