c++ define const区别

编译器处理时间:define是在预编译时处理的,const则是在编译运行时处理的。
编译器处理方式:对于define编译器每次处理时只是简单的做替换,不会做类型检测,可能会有安全隐患,并且每次替换都会重新分配内存;对于const编译器会编译检查,会报编译错误,const常量在常量内存区中存储,至始至终只会占用一份内存,不会像define那样每次替换都会重新分配内存。
数据类型:define 没有明确的数据类型,而const必须要指定数据类型
define优点:可以宏定义函数
const优点:const常量可以调试,而define常量不能调试。

 #include <iostream>
using namespace std;
#define hfut 6;//宏定义不分配内存,发生宏替换才会分配内存
#define MAX(a,b) a = a>b?a:b   //宏定义函数
int main()
{
	int a = 2,b=5;
	MAX(a, b);
	cout <<"a=  "<< a<<endl;
    int const xc = 6;//为xc分配内存,之后不需要给xc分配内存
	int n1 = hfut;//宏替换 为hfut分配内存
	int n2 = hfut;//宏替换 为hfut分配内存
	int n3 = xc;//不需要在为xc分配内存
	return 0;
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_42673507/article/details/85447981