#include "stdafx.h"
#include<stdio.h>
#define PR(x) printf("%d\t",(int)(x));
#define PRINT(a,b,c) PR(a) PR(b) PR(c)
#define MAX(a,b) (a<b?b:a)
int main()
{
int x=1,y=2;
//PR(MAX(x++,y));
PRINT(MAX(x++,y),x,y); //2,2,2
PRINT(MAX(x++,y),x,y); //2,3,2
return 0;
}
x is 1 so the 3 values to be passed as arguments in PRINT is 2 2 2.
Then in the second PRINT the values that will be passed is 2 3 2. So the output should be 2 2 2 2 3 2. But this program outputs as 2 2 2 3 4 2.
Your
MAXmacro is bad. It evaluates one of its arguments twice.expands to:
So
xis incremented twice if it started out smaller thany.There is no undefined behavior in that code because there is a sequence point between the evaluation of the first part of the ternary operator and the part that is selected. The whole
PRINTexpression expands to:Which is all fine. This does not mean you should be using such macros. Use simple functions, and let the compiler do its job of type-checking and inlining what it thinks is best.