娓娓道来c指针 (6)const的使用
2014-07-27 00:02
288 查看
(6)const的使用
c中的const表达着“常量”的意思,更准确地说是“read-only”(只读)的含义。当const与指针相遇时,由于其与*的相对位置不同,会产生不一样的效果。
举例说明
(1)const位于*的左侧
如,const int *p;此时等同于int const *p;
此时,const的含义体现在:*p是只读的。
(1)const位于*的右侧
如,int *const p;
此时,const的含义体现在:p是只读的。
实验验证
此时,添加语句*pa=2;会报错,因为*pa是只读的,不可更改;pb=&bar;同样会报错,因为pb是只读的,不可更改。
上面提到,const的本意是“只读”,而并非“常量”。通过一些方法,可以更改它的值。
从结果看,成功更改了本已声明为只读的foo。这段代码,在c中编译只是有警告,在cpp下编译直接出错。如果写成int *pa = (int *)&foo; 这是连警告都没有!不知还有没有其它的方法,大家可推荐下。
const与结构体类型相遇,此时const会const到什么程度?
编译时无任何警告,从运行结果看,const修饰符起到的作用是这样的:
若直接初始化 per = { "zx", "QiChun" };则在setPerson()方法中,修改name和address所指向的内容也是不可以的。这里的原因不是因为const,而是"zx"和"QiChun"都是常量字符串。一般情况下,常量字符串都位于内存中的只读区域,本身是不可修改的。故在代码中,我们选择申请栈空间。
专栏目录:
C指针
数据结构与算法
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; }
此时,添加语句*pa=2;会报错,因为*pa是只读的,不可更改;pb=&bar;同样会报错,因为pb是只读的,不可更改。
上面提到,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下编译直接出错。如果写成int *pa = (int *)&foo; 这是连警告都没有!不知还有没有其它的方法,大家可推荐下。
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指针
数据结构与算法
相关文章推荐
- C++ const 限定符 指针的使用方法
- C++的那点事,const,指针和引用的混合使用
- const和指针结合使用的例子
- const与指针一起使用的组合情况:
- const使用注意事项 指针 引用,指针引用区别
- 21天学通c++之第二周 指针 8.10 使用指向const对象的指针
- C语言中const与指针使用方法总结
- 使用 const 修饰的指针
- C语言的const关键字与指针搭配使用
- 关于const关键字与指针的相关使用要点
- const与指针搭配使用总结
- C++对指针使用const 限定符
- C语言的const关键字与指针搭配使用
- C语言基础---const常指针的使用
- C语言的const关键字与指针搭配使用
- c++ const和指针复合使用说明
- C语言 const 指针使用技巧之——返回指针的函数
- [C++]const的指针使用
- C++中常量指针,指针常量(const 和*)的使用方法和理解方法
- const 和二级指针的使用