宏中参数的意外多次评估

宏中参数的意外多次评估

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

问题描述

为什么第二个 printf 的输出是: max of 50 和 67 is 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
",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
",x, incr(), MAX(x, incr()));

宏替换后变为:

printf("max of %d and %d is %d
",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) 的值或第三个 incr() 的值.

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

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

08-29 07:28