欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

inline functin vs #define

程序员文章站 2022-03-16 08:48:01
...

Why should I use inline functions instead of plain old #define macros?

Unlike #define macros, inline functions avoid infamous macro errors since inline functions always evaluate every argument exactly once. In other words, invoking an inline function is semantically just like invoking a regular function, only faster:

    // A macro that returns the absolute value of i
    #define unsafe(i)  \
            ( (i) >= 0 ? (i) : -(i) )
    // An inline function that returns the absolute value of i
    inline
    int safe(int i)
    {
      return i >= 0 ? i : -i;
    }
    int f();
    void userCode(int x)
    {
      int ans;
      ans = unsafe(x++);   // Error! x is incremented twice
      ans = unsafe(f());   // Danger! f() is called twice
      ans = safe(x++);     // Correct! x is incremented once
      ans = safe(f());     // Correct! f() is called once
    }

Also unlike macros, argument types are checked, and necessary conversions are performed correctly.

Macros are bad for your health; don’t use them unless you have to.

相关标签: inline function