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.
推荐阅读
-
条款02:尽量以const,enum,inline替换#define
-
Effective C++笔记之二:尽量以const、enum、inline替换#define
-
Effective C++ 条款02 尽量以const,enum,inline替换#define
-
《Effective C++》读书笔记 条款02 尽量以const,enum,inline替换#define
-
php框架 - PHP中define vs const 定义一个常量有什么区别?
-
php框架 - PHP中define vs const 定义一个常量有什么区别?
-
条款02:尽量以const,enum,inline替换#define
-
inline functin vs #define
-
条款02:尽量以const,enum,inline 替换 #define
-
《Effective C++》读书笔记 条款02 尽量以const,enum,inline替换#define