chap9 inline function

本文探讨了C/C++中宏(macro)的常见问题及其潜在风险,例如空格引起的错误、优先级问题及副作用,并对比了内联函数(inline function)的优势。内联函数不仅保持了宏的高效特性,还解决了宏的一些缺陷,如作用域问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 
macro
缺点:
(1)#define F (x) (x + 1)
              ~~多余的空格,造成的错误很难找到

(2)对于macro里的每一项都要用括号括起来,如
  #define FLOOR(x,b) x>=b?0:1,如此调用
if(FLOOR(a&0x0f,0x07))....,等价于
if(a&0x0f>=0x07?0:1)...,由于>=的优先级高于&造成结果错误

(3)side effect,如
#define BAND(x) (((x)>5 && (x)<10) ? (x) : 0)
调用BAND(++a),有可能造成a自增两次,主要原因是macro只是简单
的替换,而不是真正的函数

优点:效率高!

inline function
继承macro的优点,扬弃macro的缺点,唯一不足的是,由于编译器
将inline函数放在符号表里,包括声明和函数体,占用空间,但是
因为inline函数一般都是比较简单的,这样的函数做为inline函数比
做为一般的函数使用更少的空间,因为一般的函数都需要参数的出入
栈操作以及调用CALL。

既然inline函数和macro差不多,为什么还要inline呢?
因为macro对于类的作用域没有概念,如
class X{
  int i;
public:
  #define VAL(X::i) //error
macro只会把X::i当作一个整体,而不知道是指类X的i

It is important to understand that an inline is just a suggestion to the compiler;
the compiler is not forced to inline anything at all. A good compiler will inline
small, simple functions while intelligently ignoring inlines that are too complicated.
This will give you the results you want – the true semantics of a function call with
the efficiency of a macro.


inline函数一般用于取得或设置私有数据的函数上, 用法
//test.h
class test
{
int i;
public:
test(int ii=0):i(ii){}
int getData(){return i;} //写在类内部的默认为inline
void setData();
void outData();
};

inline void test::setData() //以inline开头,注意inline函数要写在定义类的头文件里
{
i = i * 2;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值