· const分配内存的时机是在编译器编译时期
#include <iostream>
int main(){
int a;
const int b = 10;
int c;
//看地址的分配即可看出来是在编译期间分配内存
std::cout << &a << &b << &c;
}
· const和#define的相同之处
int main(){
//int a = 10;
//int b = 20;
//int array[a+b]; //编译不通过,但是这种语法在linux内核里面是成立的,原因 编译Linux内核的gcc编译器支持
//C和C++编译器都不支持这种语法现象
const int c = 10;
const int d = 20;
int array2[c+d]; //编译通过
}
· const和#define的区别
C++的const常量类似于宏定义
const int c = 5; ≈ #define c 5
C++中的const常量与宏定义不同
const常量是由编译器处理的,提供类型检查和作用域检查
宏定义由预处理器处理,单纯的文本替换
· const定义的变量,由编译器处理的,提供类型检查和作用域检查
void fun1(){
#define a 10
const int b = 20;
//#undef a 将a的宏定义卸载
//#undef 卸载所有的宏定义
}
void fun2(){
std::cout << a; //在a的宏定义没有被卸载时可以用
//std::cout << b; //编译错误
}
int main(){
fun1();
fun2();
return 0;
}