Execution of printf with ++ Operators in C



In the C programming language, the printf() function is used to print ("character, string, float, integer, octal, and hexadecimal values") to the output screen. To demonstrate the value of an integer variable, we use the printf() function with the %d format specifier.

Let's see a C statement and guess the result:

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

Here, in the above C statement, both 'i' and 'i++' are in the argument list; this statement causes undefined behaviour. The sequence in which the arguments are evaluated is not specified; orders may alter depending on the compiler. At different times, a single compiler can pick multiple orders.

That is why, in this C statement, printf("%d %d %d", i, ++i, i++);, the order of evaluating i, ++i, and i++ is unknown, which leads to inconsistent and unpredictable results, as different compilers or even the same compiler may choose different evaluation orders at different times.

Execution of printf with ++ Operators in C

C Program to demonstrate the three printf() statements that cause undefined behaviour:

#include <stdio.h>
int main() {
   volatile int a = 20;
   printf("%d %d\n", a, a++);

   a = 20;
   printf("%d %d\n", a++, a);

   a = 20;
   printf("%d %d %d\n", a, a++, ++a);
   return 0;
}

Following is the output:

21 20
20 20
22 21 21

Explanation: Compilers read each parameter of printf() from right to left. In the first printf() statement, the last parameter a++ will be executed first; it will print 20 and after that increase the value from 20 to 21. Now print the second-to-last argument, and show 21. The other lines are also calculated in this manner. For ++a, it will increase the value before printing, and for a++, it prints the value at first, then increases the value.

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.
Updated on: 2025-06-09T18:40:02+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements