None of the outputs can really qualify as unexpected. All the arguments to a function are evaluated before entry to the function itself -- but the order of their evaluation relative to each other is unspecified, so all of these results are allowed. Officially, your last one (that has two separate instances of incrementing a
) has undefined behavior, so it doesn't have to do anything sensible at all.
Function parameters are not evaluated in a defined order in C. Therefore one cannot tell beforehand if a
or a++
will be evaluated first when calling printf
.
You are invoking undefined behaviour by referencing both 'a' and 'a++' in the argument list.
It is not defined which order the arguments are evaluated in. Different compilers may choose different orders. A single compiler can choose different orders at different times.
Do not do it!
Nothing goes "from right to left" in function argument evaluation. When function arguments are evaluated, the order of evaluation is unspecified and there are no sequence points between evaluating separate arguments. 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.
However, your code suffers from even worse problems. All three statements that call printf
produce undefined behavior (UB) because they either make an attempt to modify the same object (a
) twice without a sequence point between the modifications (the third call), or they attempt to modify an object and read it for an independent purpose (the first and the second call). So, it is too early to even mention the order of evaluation. Your code's behavior is undefined.
++a means increment a first, and then return evaluate the expression. (a changes, and the expression evaluates as a + 1)
a++ means evaluate a (so, erm, a), and then increment it. So a is passed, but the value of a is then (ie afterwards) changed to a+1.