1、const的普通用法
const int n = 10; //n是一个只读变量,程序不可以直接修改其值
2、const与指针
int b=100;
const int* a=&b; 或int const *a=&b; //指针所指向的内容为常量
int* const a=&b; //指针本身是常量
const int* const a=&b; //指针本身和其所指向的内容为常量
3、const与函数
const int ff(); //const修饰函数返回值,返回的是常量
int ff(void)const; //const放在函数名后修饰函数,表示在函数体中成员变量不能改变
void foo(const int *p); //const用于函数的地址传递参数 ,用来限定函数的形参,这样该函数将不会修改实参指针所指的数据
4、const 与 #define 的比较
const 常量有数据类型,而宏常量没有数据类型
宏定义只是用宏名代替一个字符串,也就是只作简单的置换,不作正确性检查
5、#define与typedef
#define Count int //用Count来代替int,在预处理时处理的,它只能作简单的字符串替换,不必在行末加分号,否则连分号一起置换
typedef int Count; //声明新类型名Count为int类型,在编译阶段处理的,它是先生成一个类型名,在用它去定义变量
const int n = 10; //n是一个只读变量,程序不可以直接修改其值
2、const与指针
int b=100;
const int* a=&b; 或int const *a=&b; //指针所指向的内容为常量
int* const a=&b; //指针本身是常量
const int* const a=&b; //指针本身和其所指向的内容为常量
3、const与函数
const int ff(); //const修饰函数返回值,返回的是常量
int ff(void)const; //const放在函数名后修饰函数,表示在函数体中成员变量不能改变
void foo(const int *p); //const用于函数的地址传递参数 ,用来限定函数的形参,这样该函数将不会修改实参指针所指的数据
4、const 与 #define 的比较
const 常量有数据类型,而宏常量没有数据类型
宏定义只是用宏名代替一个字符串,也就是只作简单的置换,不作正确性检查
5、#define与typedef
#define Count int //用Count来代替int,在预处理时处理的,它只能作简单的字符串替换,不必在行末加分号,否则连分号一起置换
typedef int Count; //声明新类型名Count为int类型,在编译阶段处理的,它是先生成一个类型名,在用它去定义变量