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 = 10
andj = 5
, so the comparision would be10
v/s6
which would be true or1
with side effecti
becomes11
andj
becomes6
. (Recall that: Macros are not functions)As
k = 0
and not equal to1
,k==(i++) > (++j)
would befalse
and++j
would be executed. Causingj
to 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 6
fori j
, so you are changing the variables using++
operator, don't expect both statements to have the same values.