This question already has answers here:
What is double evaluation and why should it be avoided?
(4个答案)
去年关闭。
阅读combase.cpp代码,我发现以下内容:
我不明白为什么“最大宏导致对其中一个参数进行两次评估”?
目的可能是打印
因此,
在某些情况下,可以多次评估作为参数传递给宏的表达式。
(4个答案)
去年关闭。
阅读combase.cpp代码,我发现以下内容:
/* We have to ensure that we DON'T use a max macro, since these will typically */
/* lead to one of the parameters being evaluated twice. Since we are worried */
/* about concurrency, we can't afford to access the m_cRef twice since we can't */
/* afford to run the risk that its value having changed between accesses. */
template<class T> inline static T ourmax( const T & a, const T & b )
{
return a > b ? a : b;
}
我不明白为什么“最大宏导致对其中一个参数进行两次评估”?
最佳答案
考虑这样的用法 code sample :
#define max(a,b) (a>b?a:b)
int main()
{
int a = 0;
int b = 1;
int c = max(a++, b++);
cout << a << endl << b << endl;
return 0;
}
目的可能是打印
1
和2
,但是宏扩展为:int c = a++ > b++ ? a++ : b++;
b
递增两次,程序将打印1
和3
。因此,
在某些情况下,可以多次评估作为参数传递给宏的表达式。
关于c++ - 获取最大var时,使用函数和宏有什么区别,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10695945/