内联函数和宏定义
1 目标
本文的目的是学习内联函数,并和宏做对比。
2 示例代码
内联函数(inline function)是指编译器在编译时将函数调用替换为函数体代码,以减少函数调用的开销,提高运行效率。内联函数通过在函数定义前加上 inline 关键字声明。
2.1 非内联函数示例
#include <iostream>
int multiply(int a, int b) {
return a * b;
}
int main() {
int x = 5;
int y = 4;
std::cout << "x * y = " << multiply(x, y) << std::endl; // 进行函数调用,有函数调用开销
return 0;
}
2.2 内联函数示例
#include <iostream>
inline int multiply(int a, int b) {
return a * b;
}
int main() {
int x = 5;
int y = 4;
std::cout << "x * y = " << multiply(x, y) << std::endl; // 编译器将直接将 multiply(x, y) 替换为 x * y
return 0;
}
2.3 内联函数和宏
#include <iostream>
// 宏定义
#define ADD(a, b) ((a) + (b))
// 内联函数定义
inline int add(int a, int b) {
return a + b;
}
int main() {
int x = 5;
int y = 10;
std::cout << "x + y (using macro) = " << ADD(x, y) << std::endl;
std::cout << "x + y (using inline function) = " << add(x, y) << std::endl;
return 0;
}
3 总结
3.1宏定义
- 优点:简单,不进行类型检查,可以用于任何数据类型。
- 缺点:预处理器直接展开宏,可能导致不易察觉的错误,如运算符优先级问题。没有类型检查,不如函数安全。
3.2 内联函数
- 优点:有类型检查,安全性高,容易调试。编译器优化,适用于任何复杂表达式。
- 缺点:仅限于函数调用的场景,不如宏灵活。