Chinaunix首页 | 论坛 | 博客
  • 博客访问: 359876
  • 博文数量: 100
  • 博客积分: 2500
  • 博客等级: 大尉
  • 技术积分: 1209
  • 用 户 组: 普通用户
  • 注册时间: 2011-04-15 21:24
文章分类

全部博文(100)

文章存档

2011年(100)

分类: C/C++

2011-04-22 10:04:01

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.
阅读(1315) | 评论(1) | 转发(0) |
0

上一篇:This 指针

下一篇:抽象基类

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

onezeroone2011-04-24 15:56:07

read from right-to-left