码迷,mamicode.com
首页 > 其他好文 > 详细

用const修饰指针

时间:2014-09-18 21:52:34      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:style   ar   sp   on   c   line   r   bs   har   

其实很简单,无奈老是记不住,那就单独写出来吧!

a.指针本身不可变,即不可指向其他对象:

char* const pContent = “abcde”;

pContent[2] = ‘f’;     //合法

pContent = “abfde”;    //不合法

 

b.指针所指向的对象不可变,即指针不可以修改所指向的对象

const char *pContent = “abcde”; //或者

char const *pContent = “abcde”;     //上下两种情况相同

pContent[2] = ‘f’;     //不合法

pContent = “abfde”;    //合法

 

c.两者都不可变

const char* const pContent; //指向const对象的const指针

pContent[2] = ‘f’;     //不合法

pContent = “abfde”;    //不合法

 

识别const到底是修饰指针本身还是指针所指的对象,还有一个较为简便的方法,也就是沿着*号划一条竖线,把声明语句从*号处分成左右两部分:

如果const位于*的左侧,则const修饰指针所指向的对象,即指针指向对象不可变;

如果const位于*的右侧,则const修饰指针本身,即指针本身不可指向其他对象。

用const修饰指针

标签:style   ar   sp   on   c   line   r   bs   har   

原文地址:http://www.cnblogs.com/superpig0501/p/3980034.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!