Chinaunix首页 | 论坛 | 博客
  • 博客访问: 88285
  • 博文数量: 60
  • 博客积分: 4002
  • 博客等级: 中校
  • 技术积分: 645
  • 用 户 组: 普通用户
  • 注册时间: 2010-03-17 18:11
文章分类

全部博文(60)

文章存档

2011年(60)

我的朋友

分类: C/C++

2011-03-30 22:31:30


CONSTANT KEYWORD

char *p       = "Hello"  // non-const pointer, non-const data
const char *p  = "Hello"; // non-const pointer, const data
char * const p = "Hello"; // const pointer non-const data
const char * const p = "Hello"; // const pointer, const data



I have this explanation I wrote a long time ago stored away in a file, so to elaborate:

This file explains how const works.

The following declarations are identical:

const char* p;
char const* p;



Both declare a pointer to a constant character. The second is slightly
better in the sense that the declaration can be read from right-to-left:
"p is a pointer to a const char". Read as such, it is easy to see that
the line *p = 'c'; will not compile.

The following declaration:

char* const p;




declares p to be a constant pointer to a character. That is:

p = "foo"; // Does not compile
*p = 'f'; // Compiles!



And thus:

const char* const p;
char const* const p;



both declare p to be a constant pointer to a constant character, and
so none of the following lines of code compile:

p = "foo";
*p = 'f';



Now throw another pointer into the mix:

const char** p;
char const** p;



These are equivalent and declare p to be a pointer to a pointer to a
constant character. That is:

p = ptr-to-ptr-to-char; // Compiles
*p = ptr-to-char; // Compiles
**p = 'f'; // Does not compile



Or how about creative placement of const:

char* const* p;



This declares p to be a pointer to a constant pointer to a character.
That is:

p = ptr-to-constptr-to-char; // Compiles
*p = ptr-to-char; // Does not compile
*p = constptr-to-char; // Does not compile
**p = 'f'; // Compiles




And the ever-popular:

char** const p;




Which declares p to be a constant pointer to a pointer to a character.
Or:

p = ptr-to-ptr-to-char; // Does not compile
p = constptr-to-ptr-to-char; // Does not compile
*p = ptr-to-char; // Compiles
**p = 'f'; // Compiles




And now we get just plain const happy:

const char* const* p;



p is a pointer to a constant pointer to a constant character. The only
thing you can do with this one (besides remove the code and rewrite) is:
p = ptr-to-constptr-to-constchar;

const char** const p;



p is a constant pointer to a pointer to a constant character. The only
thing you can do with this is:
*p = ptr-to-constchar;

And this beast:

const char* const* const p;



Well, it won't pass code review since nobody will understand it, but at
any rate... We've achieved maximum constant-ness with this line. You
can't do anything at all with p, what it points to, what that points to,
or what "what that" points to. You can print it. That's about it.

阅读(412) | 评论(0) | 转发(0) |
0

上一篇:this pointer

下一篇:Abstract Class

给主人留下些什么吧!~~