const和define的区别

转自xd_xumaomao const(常量)和#define(宏定义)区别

对比

编译器处理不同

宏定义是一个“编译时”概念,在预处理阶段展开(在编译时把所有用到宏定义值的地方用宏定义常量替换),不能对宏定义进行调试,生命周期结束于编译时期;
const常量是一个“运行时”概念,在程序运行使用,类似于一个只读行数据

存储方式不同

宏定义是直接替换,不会分配内存,存储与程序的代码段中;
const常量需要进行内存分配

类型和安全检查不同

宏定义是字符替换,没有数据类型的区别,同时这种替换没有类型安全检查,可能产生边际效应等错误;
const常量是常量的声明,有类型区别,需要在编译阶段进行类型检查

定义域不同

 1 void f1 ()
 2 {
 3 
 4     #define N 12
 5     const int n 12;
 6     
 7 }
 8 
 9     void f2 ()
10 {
11     cout<<N <<endl; //正确,N已经定义过,不受定义域限制
12     cout<<n <<endl; //错误,n定义域只在f1函数中
13 }

是否可以做函数参数

宏定义不能作为参数传递给函数
const常量可以在函数的参数列表中出现

定义后能否取消

宏定义可以通过#undef来使之前的宏定义失效
const常量定义后将在定义域内永久有效

void f1()
{
  #define N 12
  const int n = 12;
  
  #undef N //取消宏定义后,即使在f1函数中,N也无效了
  #define N 21//取消后可以重新定义
}

const

1. const int p; // p is a int const. p是一个int型常量 这个很简单
2. const int *p; //p is a point to int const. p是一个指针,指向int型常量。即p是一个指向int型常量的指针。
3. int const *p; //与2相同 const int 和 int const 是一样的意思。《C++ primer》中采用第一种写法。
4. int * const p; // p is a const point to int. p是一个指向int的const指针
5. const int * const p; //p is a const point to int const. p是一个指向int型常量的const指针。
6. int const * const p; //同5

总结

宏定义在编译时把所有用到宏定义值的地方用宏定义常量替换。const常量可以看作是一个只读变量,需要指定类型,需要分配内存,有自己的作用域。

原文地址:https://www.cnblogs.com/chen-cs/p/13199185.html