Why outputs of i and j in the following two printf()s are different?
#include <cstdio>
#define MAX(x,y) (x)>(y)?(x):(y)
int main()
{
int i=10,j=5,k=0;
k==MAX(i++,++j);
printf("%d %d %d\n",i,j,k);
i=10,j=5,k=0;
k=MAX(i++,++j);
printf("%d %d %d\n",i,j,k);
return 0;
}
I think only k should differ, but it is showing different output for all, i, j and k, in printf() statement. What is the reason?
Output :
11 7 0
12 6 11
k==MAX(i++,++j);is translated to:In your case
i = 10andj = 5, so the comparision would be10v/s6which would be true or1with side effectibecomes11andjbecomes6. (Recall that: Macros are not functions)As
k = 0and not equal to1,k==(i++) > (++j)would befalseand++jwould be executed. Causingjto be incremented to7.In latter case, there is no modification to the value of variables.
When can I expect same output in both case? Even if you change the macro with a function, your arguments have the side effects, which would cause the output
11 6fori j, so you are changing the variables using++operator, don't expect both statements to have the same values.