简体   繁体   中英

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? 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM