Macros can do two things: 1. Define constants 2. Define functions
#define A 10
#define ADD(x,y) (x+y)
C++ recommends:
1. Replace macro constants with const
2. Replace macro functions with inline functions
Inline function definition: Add the inline keyword before the function definition. Note: Add invalid before the declaration.
Macro functions are processed during preprocessing.
Inline functions are processed during compilation and have the corresponding function parameter checking and type checking of ordinary functions. .
There is overhead when running a function: overhead for pushing, popping, jumping, etc.
1. The inline function is replaced with the function body during execution.
2. Inlining is a request and may not be successful.
3. The function body does not exist in the compiled program.
Notes:
1. The function body cannot be too large, less than 5 lines.
2. There cannot be loop statements
. 3. There cannot be complex conditional judgment statements
. 4. The address acquisition operation cannot be performed on inline functions. ===> No function body
#include <stdio.h>
// 宏 可以做两件事情:1、定义常量 2、定义函数
#define A 10
#define ADD(x,y) (x+y)
// C++ 建议用:
// 1、const 替换宏常量
// 2、用 内联函数 替换宏函数
// 内联函数定义:在函数定义前加 inline 关键字 注意:在声明前加无效
// 宏函数是在预处理期间进行处理
// 内联函数在编译进行处理,具备普通函数的相应功能 参数检查 类型检查。。
// 函数运行是有开销的:入栈、出栈、跳转等开销
// 1、内联函数在执行用函数体进行替换,
// 2、内联是一种请求,不一定成功
// 3、编译完后的程序中不存在函数体
// 注意事项:
// 1、函数体不能太庞大,5行以下
// 2、不能有循环语句
// 3、不能有复杂的条件判断语句
// 4、不能对内联函数进行取地址操作 ===> 没有函数体
// 实现机制:在符号表中进行实现
inline int add(int a, int b)
{
return a + b;
}
int main()
{
printf ("%d\n", ADD(1,2));
printf ("%d\n", add(1,2));
return 0;
}