Unintended multiple evaluation of parameter in mac

2020-04-02 06:05发布

Why the the output of the second printf is: max of 50 and 67 is 62 ? Why not max of 50 and 62 is 57?

#define MAX(a,b) ((a)>(b) ? (a): (b))
int incr(){
    static int i =42;
    i += 5;
    return i;
}
int _tmain(int argc, _TCHAR* argv[])
{   
    int x = 50;
    printf("max of %d and %d is %d\n",x, incr(), MAX(x, incr()));
    printf("max of %d and %d is %d",x, incr(), MAX(x, incr()));
    return 0;
}

标签: c macros
1条回答
趁早两清
2楼-- · 2020-04-02 06:35
printf("max of %d and %d is %d\n",x, incr(), MAX(x, incr()));

After the macro substitution, it becomes:

printf("max of %d and %d is %d\n",x, incr(), ((x)>(incr()) ? (x): (incr())));
//                                    ^1            ^2               ^3

incr() is called multiple times in this single function call, it's unspecified which argument is evaluated first. Whether the first or the second is called first make the result unexpected.

The only thing to be certain is due to the short circuit of ?:, (x)>(incr() is evaluated to determine if the expression has the value of (x) or the value of the third the incr().

查看更多
登录 后发表回答