Introduction
The printf() function in the C programming language is used to print ("character, string, float, integer, octal, and hexadecimal values") to the output screen. To show the value of an integer variable, we use the printf() function with the % d format specifier.
Consider the C statement below and guess the result.
printf("%d %d %d", i, ++i, i++);By addressing both ‘i’ and 'i++' in the argument list, this statement causes undefined behavior. 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.
Various printf() statements, including lines using the ++ operator, can be found in some situations. These questions can be seen in multiple competitive test questions to determine the code's output.
In this blog, we will learn about the behavior ++operator with printf function.
Also see: C Static Function and Short int in C Programming
Example
In this part, we'll look at an example of that question and try to figure out the solution.
Three printf() commands, in the example below, may result in ambiguous behavior:
#include <stdio.h>
int main()
{
volatile int x = 1;
printf("%d %d\n", x, x++);
x = 1;
printf("%d %d\n", x++, x);
x = 1;
printf("%d %d %d\n", x, x++, ++x);
return 0;
}Output:
2 1
1 1
3 2 2Compilers usually read printf() parameters from right to left. As the last parameter of the first printf() expression, 'x++' will be run first. It will print 1. However, because the value has now been increased by one, the second last argument, i.e., will now print 2. The other statements will be performed in the same way.
Note that in pre-increment, ++x, the value increases by one before printing, but in post-increment, x++, the value is printed first and then incremented by 1.
As a result, using two or more pre or post-increment operators in the same statement is not advised. This indicates that there is no chronological sequence in this procedure. The arguments can be assessed in any sequence, and the evaluation process can be entwined.
Now we'll try to estimate what the result will be. The majority of compilers order printf() parameters from right to left. So, because the last parameter in the first printf() expression is x++, it will be run first, printing 1 and then increasing the number from 1 to 2. Show 2 after printing the second final argument. Similarly, other lines are computed in the same way. It will raise the value before printing for ++x, and it will print the value first, then increase the value for x++.
Also see, Tribonacci Series





