Chinaunix首页 | 论坛 | 博客
  • 博客访问: 34773
  • 博文数量: 23
  • 博客积分: 1415
  • 博客等级: 上尉
  • 技术积分: 235
  • 用 户 组: 普通用户
  • 注册时间: 2009-02-20 09:41
文章分类
文章存档

2011年(1)

2010年(2)

2009年(20)

我的朋友

分类: C/C++

2009-02-21 09:16:18

about "const" in c:


An interesting extra feature pops up now. What does this mean?

char c;
char *const cp = &c;

It's simple really; cp is a pointer to a char, which is exactly what it would be if the const weren't there. The const means that cp is not to be modified, although whatever it points to can be—the pointer is constant, not the thing that it points to. The other way round is

const char *cp;

which means that now cp is an ordinary, modifiable pointer, but the thing that it points to must not be modified. So, depending on what you choose to do, both the pointer and the thing it points to may be modifiable or not; just choose the appropriate declaration.


The trick is to read the declaration backwards (right-to-left):

const int a = 1; // read as "a is an integer which is constant"
int const a = 1; // read as "a is a constant integer"

Both are the same thing. Therefore:

a = 2; // Can't do because a is constant

The reading backwards trick especially comes in handy when you're dealing with more complex declarations such as:

const char *s;      // read as "s is a pointer to a char that is constant"
char c;
char *const t = &c; // read as "t is a constant pointer to a char"

*s = 'A'; // Can't do because the char is constant
s
++;      // Can do because the pointer isn't constant
*t = 'A'; // Can do because the char isn't constant
t
++;      // Can't do because the pointer is constant
阅读(414) | 评论(0) | 转发(0) |
0

上一篇:static

下一篇:C++ GUI Programming with QT4 (1)

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