Here\'s some more weird macro behavior I was hoping somebody could shed light on:
#define MAX(a,b) (a>b?a:b)
void main(void)
{
int a = 3, b=4;
print
I think the questioner was expecting the output to start:
3 4 ...
instead of:
4 6 ...
and this is because the parameters are being evaluated from right to left as they are being pushed onto the stack, that is, the last parameter is being evaluated first and pushed, then the second to last, then the second parameter and finally the first parameter.
I think (and someone post a comment if it's wrong) that this is defined in the C standard (and C++).
Update
The order of evaluation is defined, but it's defined as undefined (thanks Steve). Your compiler just happens to do it this way. I think I got confused between evaluation order and the order the parameters are passed.
When the preprocessor reads the line it replace the MAX(a++,b++) in the printf to the (a++>b++?a++;b++)
So your function becomes
printf(a,b,(a++>b++?a++;b++));
Here order of evaluation is "compiler dependent".
To understand when these conditions can occur u have to understand about Sequence point.
At each sequence point, the side effects of all previous expressions will be completed(all the variable calculation will be completed). This is why you cannot rely on expressions such as:
a[i] = i++;
because there is no sequence point specified for the assignment, increment or index operators, you don't know when the effect of the increment on i occurs. “Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be read only to determine the value to be stored.”. If a program breaks these rules, the results on any particular implementation are entirely unpredictable(undefined).
--The sequence points laid down in the Standard are the following:
1) The point of calling a function, after evaluating its arguments.
2) The end of the first operand of the && operator.
3)The end of the first operand of the || operator.
4)The end of the first operand of the ?: conditional operator.
5)The end of the each operand of the comma operator.
6)Completing the evaluation of a full expression. They are the following:
Evaluating the initializer of an auto object.
The expression in an ‘ordinary’ statement—an expression followed by semicolon.
The controlling expressions in do, while, if, switch or for statements.
The other two expressions in a for statement.
The expression in a return statement.