(6)const的使用
c中的const表达着“常量”的意思,更准确地说是“read-only”(只读)的含义。当const与指针相遇时,由于其与*的相对位置不同,会产生不一样的效果。
举例说明
(1)const位于*的左侧
如,const int *p;此时等同于int const *p;
此时,const的含义体现在:*p是只读的。
(1)const位于*的右侧
如,int *const p;
此时,const的含义体现在:p是只读的。实验验证
int main()
{
int foo = 1;
int bar = 2;
const int *pa = &foo;
int *const pb = &foo;
//尝试修改值
*pa = 2; //编译器报错:“表达时必须是可修改的左值”
pb = &bar; //编译器报错:“表达时必须是可修改的左值”
return 0;
}
上面提到,const的本意是“只读”,而并非“常量”。通过一些方法,可以更改它的值。
int main()
{
const int foo = 1;
printf("foo...%d\n", foo);
int *pa = &foo; //这里有警告,但仍可运行
*pa = 2;
printf("foo...%d\n", foo);
system("pause");
return 0;
}运行
从结果看,成功更改了本已声明为只读的foo。这段代码,在c中编译只是有警告,在cpp下编译直接出错。不知还有没有其它的方法,大家可推荐下。
const与结构体类型相遇,此时const会const到什么程度?
typedef struct
{
char *name;
char *address;
int age;
}Person;
void setPerson(const Person* pPer)
{
/*以下方式会出错!
pPer->name = "David";
pPer->address = "BeiJing";
pPer->age = 22;
*/
strcpy(pPer->name, sizeof("David"), "David");
strcpy(pPer->address, sizeof("BeiJing"), "BeiJing");
}
int main()
{
Person per;
char name[10] = "zx";
char address[20] = "QiChun";
per.name = name;
per.address = address;
per.age = 24;
printf("per.name...%s\n", per.name);
printf("per.address...%s\n", per.address);
printf("per.age...%d\n", per.age);
printf("update..\n");
setPerson(&per);
printf("per.name...%s\n", per.name);
printf("per.address...%s\n", per.address);
printf("per.age...%d\n", per.age);
return 0;
}运行编译时无任何警告,从运行结果看,const修饰符起到的作用是这样的:
若直接初始化 per = { "zx", "QiChun" };则在setPerson()方法中,修改name和address所指向的内容也是不可以的。这里的原因不是因为const,而是"zx"和"QiChun"都是常量字符串。一般情况下,常量字符串都位于内存中的只读区域,本身是不可修改的。故在代码中,我们选择申请栈空间。
专栏目录:C指针
原文地址:http://blog.csdn.net/zhangxiangdavaid/article/details/38082159