LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 749|回复: 5

const 没起作用?

[复制链接]
发表于 2004-4-3 21:53:06 | 显示全部楼层 |阅读模式

  1. int
  2. main(void)
  3. {
  4.     int i=3;
  5.     int b=9;
  6.     const int *pr=&i;
  7.     if(i=8)
  8.          printf("target can given a  new value\n");
  9.     if(pr=&b)
  10.          printf("finger can point to other int value\n");
  11.     return(0);
  12. }
  13. # ./a.out
  14. target can given a  new value
  15. finger can point to other int value
复制代码

const的值不是不能改变吗?
还是我的程序不能体现问题?要是这个const起作用,应该怎么做呢?
发表于 2004-4-3 22:01:51 | 显示全部楼层
"const int *pr"  !=  "int * const pr"
 楼主| 发表于 2004-4-3 22:09:15 | 显示全部楼层
最初由 _z_ 发表
"const int *pr"  !=  "int * const pr"


thanks !please give me a example for "int *const pr" ,thank in advance.

定义成:int const *pr
结果和上面的一样?:rolleyes:
发表于 2004-4-4 11:52:05 | 显示全部楼层
楼上的兄弟要注意啦,const放在星号的左边和右边是不一样的。
放在星号的左边表示指针指向的是常量,但指针本身可以指向别的变量或常量。具体表示方法如:const int *p 或 int const *p表示的效果都是一样的。但指针放在右边就表示指针本身是常量,指针在初始化后不可能再指向别的变量或常量。如:int * const p表示的就是这个意思。如果要指针既然指向常量,指针本身也量常量,可以象这样来表示:const int * const p。
发表于 2004-4-4 12:03:35 | 显示全部楼层
"const int *pr" == "int const *pr"
but "const int *pr" != "int * const pr"

"const int *pr" means the object pointed by "pr" is a constant
example:
const int *pr=&i;
*pr=2; //error!!!
pr=NULL;  //OK

"int * const pr" means the pointer "pr" is a constant
example:
int * const pr=&i;
*pr=2; //OK
pr=NULL;  //error!!!

"const int * const pr" means both the object and the pointer are constants
const int * const pr=&i;
*pr=2; //error!!!
pr=NULL;  //error!!!
 楼主| 发表于 2004-4-4 13:41:54 | 显示全部楼层
谢谢两位的详细解释。。。。
您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表