问题描述
#define max(a,b)
({ typeof (a) _a = (a);
typeof (b) _b = (b);
_a > _b ? _a : _b; })
为什么不简单地 (a>b ? a : b)
?
推荐答案
因为否则 max(f(1), f(2))
会调用这两个函数之一两次:
because otherwhise max(f(1), f(2))
would call one of the two functions twice:
f(1) > f(2) ? f(1) : f(2)
而是通过缓存" _a
和 _b
中的两个值
instead by "caching" the two values in _a
and _b
you have
({
sometype _a = (a);
sometype _b = (b);
_a > _b ? _a : _b;
})
(很明显,正如其他人指出的那样,自动增量/自动减量存在同样的问题)
(and clearly as other have pointed out, there is the same problem with autoincrement/autodecrement)
我认为 Visual Studio 不支持这种方式.这是一个复合语句.阅读此处msvc 是否具有 gcc ({ }) 的模拟
I don't think this is supported by Visual Studio in this way. This is a compound statement. Read here does msvc have analog of gcc's ({ })
我将在此处给出的 gcc 手册中添加复合语句的定义 http://gcc.gnu.org/onlinedocs/gcc-2.95.3/gcc_4.html#SEC62 显示的代码与 max 的问题非常相似:-)
I'll add that the definition of compound statement in the gcc manual given here http://gcc.gnu.org/onlinedocs/gcc-2.95.3/gcc_4.html#SEC62 shows a code VERY similar to the one of the question for max :-)
这篇关于为什么在 C 中这样定义“max"宏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!