Consider this code:
void res(int a,int n)
{
printf("%d %d, ",a,n);
}
void main(void)
{
int i;
for(i=0;i<5;i++)
res(i++,i);
//prints 0 1, 2 3, 4 5
for(i=0;i<5;i++)
res(i,i++);
//prints 1 0, 3 2, 5 4
}
Looking at the output, it seems that the arguments are not evaluated from right to left every time. What exactly is happening here?
The order of evaluation of arguments in a function call is unspecified. The compiler can evaluate them in whichever order it might decide on.
From the C99 standard 6.5.2.2/10 “Function calls/semantics”:
If you need to ensure a particular ordering, using temporaries is the usual workaround:
Even more important (since it results in undefined behavior, not just unspecified behavior) is that you generally can’t use an operand to the increment/decrement operators more than once in an expression. That’s because: