宏中参数的意外多次求值 [英] Unintended multiple evaluation of parameter in macro

查看:96
本文介绍了宏中参数的意外多次求值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么第二个printf的输出是:最大值50和67是62?为什么不将50和62的最大值设为57?

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;
}

推荐答案

printf("max of %d and %d is %d\n",x, incr(), MAX(x, incr()));

替换宏后,它变为:

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

incr()在此单个函数调用中被多次调用,但未指定先评估哪个参数.无论是第一个还是第二个都被调用,使结果出乎意料.

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.

唯一可以确定的是,由于?:的短路,对(x)>(incr()进行求值以确定表达式是否具有(x)的值或第三个cc>的值.

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().

这篇关于宏中参数的意外多次求值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆