Inline function v. Macro in C — What's the Overhead (Memory/Speed)?

后端 未结 9 1255
太阳男子
太阳男子 2020-12-02 13:18

I searched Stack Overflow for the pros/cons of function-like macros v. inline functions.

I found the following discussion: Pros and Cons of Different macro function

9条回答
  •  臣服心动
    2020-12-02 13:52

    Macros, including function-like macros, are simple text substitutions, and as such can bite you in the ass if you're not really careful with your parameters. For example, the ever-so-popular SQUARE macro:

    #define SQUARE(x) ((x)*(x))
    

    can be a disaster waiting to happen if you call it as SQUARE(i++). Also, function-like macros have no concept of scope, and don't support local variables; the most popular hack is something like

    #define MACRO(S,R,E,C)                                     \
    do                                                         \   
    {                                                          \
      double AttractiveTerm = pow((S)/(R),3);                  \
      double RepulsiveTerm = AttractiveTerm * AttractiveTerm;  \
      (C) = 4 * (E) * (RepulsiveTerm - AttractiveTerm);        \
    } while(0)
    

    which, of course, makes it hard to assign a result like x = MACRO(a,b);.

    The best bet from a correctness and maintainability standpoint is to make it a function and specify inline. Macros are not functions, and should not be confused with them.

    Once you've done that, measure the performance and find where any actual bottleneck is before hacking at it (the call to pow would certainly be a candidate for streamlining).

提交回复
热议问题