muru
muru

Reputation: 121

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.

Upvotes: 1

Views: 88

Answers (1)

Lee Duhem
Lee Duhem

Reputation: 15121

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.

Upvotes: 1

Related Questions