The expression a++
evaluates to the current value of a
and as a side effect increments a
by 1. The expression ++a
evaluates to the current value of a
+ 1 and as a side effect increments a
by 1.
If you had written
a = 1;
printf("%d\n", a++);
you would get the output 1
, because you're asking for the current value of a
. Had you written
a = 1;
printf("%d\n", ++a);
you would get the output 2
, because you're asking for the value of a + 1
.
Now, what's important to remember (especially with ++a
) is that the side effect of actually updating a
doesn't have to happen immediately after the expression has been evaluated; it only has to happen before the next sequence point (which, in the case of a function call, is after all of the arguments have been evaluated).
Per the language definition, an object (such as the variable a
) may have its value changed by the evaluation of an expression (a++
or ++a
) at most once between sequence points, and the prior value shall be read only to determine the value to be stored.
The statement
printf("%d %d\n", a, a++);
violates the second part of that restriction, so the behavior of that statement is undefined. Your output could be any of 1 1
, 1 2
, a suffusion of yellow, etc.