Const的全面理解(C部分)
下面我们来看一些简单的代码:
const int a1=1; int const a2=1; int *p=0x1; const int* a1; int* const a2; int const* const a3;Const 是C中类似的修饰符。常见的数据类型修饰符有
Short long unsigned static auto extern register.
定义一个变量
类型描述符 变量名;
类型描述符=类型的修饰符+数据类型(int,char,float)
const int a1=1; int const a2=1;表示的就是一个意思(指const int和int const是一个意思)
另外:
Static int short i; Int static short i;也都是表示一个意思(指static、int、short)
对指针变量类型的理解
[],(),*有优先级,有以下理解
int *a1[10]; //[]高于*,所以是一个数组,每一个成员都是指针
int (*a2)[10]; //()高于[],是一个指针,指向的类型为一个数组
此处可见!
对指针变量的类型理解(建议从左向右)
int p = 0x1; const int* a1=&p; //变量a1,int*,const,表名指向的数据不可改 int const *a2 = &p; //同a1 int* const a3=&p; //a3指向的地址不能修改 int const* const a4=&p; //什么都不能修改最后!
typedef void* VP;
1.const void* ptr1
2.const VP ptr2
我们用如下代码来测试
#include <stdio.h> void main() { typedef void* VP; const void* ptr1=NULL; const VP ptr2=(VP)ptr1; VP const ptr3=(VP)ptr1; getchar(); }可见当用typedef定义时都为常指针
Const的作用
1.向其他程序员传递这个是不能修改的。
2.有可能让编译器产生更加紧凑的代码,避免不必要的错误。
3.合理包含我们只读的数据,避免不必要的错误
使用的位置
1.定义常量。防止被修改
2.函数参数中,加以限制
如strcpy和strncpy等等等
