#include <stdio.h> void fun1() { #define a 10 const int b = 20; //#undef a # undef } void fun2() { printf("a = %d\n", a); //printf("b = %d\n", b); } int main() { fun1(); fun2(); return 0; }
对比加深
C++中的const常量类似于宏定义
const int c = 5; ≈ #define c 5
C++中的const常量与宏定义不同
const常量是由编译器处理的,提供类型检查和作用域检查
宏定义由预处理器处理,单纯的文本替换