define 宏定义和 const 的区别
比较define在汇编中的代码:
#define Pi 3.1415926
int main(){
const int a = 10;
}
汇编
main:
push rbp
mov rbp, rsp
mov DWORD PTR [rbp-4], 10
mov eax, 0
pop rbp
ret
可以看到define没有出现在汇编中,所以在预编译阶段进行;const是在编译阶段。
- 编译阶段:
- define在编译的预编译阶段,const是在编译、运行的时候
- 安全性:
- define制作替换,不做类型检查和计算,容易出错
- const常量有数据类型,可以进行类型检查
- 内存
- define只是将宏名称进行替换,在内存中会产生多分相同的备份;const在程序运行中只有一份备份。
- define定义的数据没有分配内存空间,只是插入替换掉;const定义的变量值不能改变,要分配内存空间,在常量区。