1
#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.

3
  • 1
    No, it's just obfuscation. Commented Apr 24, 2014 at 14:08
  • 2
    "I read" Where? Citation please. Commented Apr 24, 2014 at 14:14
  • a benefit of macros can be not having to duplicate code just to deal with different types Commented Apr 24, 2014 at 14:15

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

You example would also be undefined behavior if SUM would be a function.
Would be better to mention inline functions in the first paragraph and mention that they avoid call overhead.
@Potatoswatter My intention is to give a direct answer in the first paragraph to the question in the original post. And point out possible pitfalls, alternatives and other additional information in the following paragraph.
It's your prerogative. Personally, if an alternative is superior almost all the time due to such a serious pitfall of question topic, I'll give it top billing.
@Potatoswatter Good point. We are here not only to answer questions but also, more importantly, to share our experience. I will adopt this organization of answer when I try to answer a question next time. Thank you.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.