inline functin vs #define

本文探讨了在C++中使用内联函数替代宏定义的原因。内联函数避免了宏定义常见的错误,如参数求值次数不确定的问题,并且能够进行类型检查及正确的转换。与宏相比,内联函数在语义上更接近普通函数调用,同时提供了更快的执行速度。
摘要由CSDN通过智能技术生成

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值