[英]macros and function within loop
#define SUM(x,y) ((x)+(y))
void print(){
for(int i=0;i<10;i++)
printf("sum=%d\n", SUM(i,i+1));
}
Is there any benefit in using the macro SUM like above? 使用上面的宏SUM有什么好处? I read that macros are useful when there is a loop with a function call inside.
我读到,当内部有一个函数调用循环时,宏非常有用。
For very simple computation, call function may have more overhead than the actual computation itself; 对于非常简单的计算,调用函数可能比实际的计算本身具有更多的开销。 in a loop, the situation even worse.
在一个循环中,情况甚至更糟。
However, you need to define your function replacement macro carefully to only evaluate its arguments once. 但是,您需要仔细定义函数替换宏,以便仅对其参数进行一次评估。 For example, if you have a macro like this
例如,如果您有这样的宏
#define DOUBLE(i) ((i) + (i))
and you call it like this DOUBLE(i++)
, it will be expanded to (i++)+(i++)
, and this will cause undefined behavior in C. That is why inline function, which will evaluate its arguments only once, is preferable than macro. 并且您这样称呼它
DOUBLE(i++)
,它将被扩展为(i++)+(i++)
,这将导致C中的未定义行为。这就是为什么内联函数只对它的参数进行一次评估的原因,胜于宏。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.