通过声明
const int i;
很明显i
不能修改。
那为什么要声明
void f (const int *p)
正在修改p
?(我测试了它,它正在修改p
但不知道如何?)。
const
在指针声明中的放置很重要。你倒着读:
const int *p
表示“p 是一个指向int
它的常量的指针”int * const p
表示“p 是指向int
”的常量指针const int * const p
表示“p 是指向常量的常量指针int
”因为const
是int
指向的p
,而不是p
指向的指针int
。
const int *p
表示 thatp
是指向 的指针const int
,p
可以修改,*p
不能。
一样的方法
int *const p
表示p
不能修改,而*p
可以。
请注意,const int* p
与 相同int const* p
。
简单的规则是声明从右向左读取:int const *p
表示“p 是指向常量 int 的指针”,int *const p
表示“p 是指向 int 的常量指针”。
(实际的完整规则比较复杂,可以使用http://cdecl.org/来“解码”C 风格的声明。)
因为在这个表达式中,p
是一个指向 a 的指针const int
。这意味着您可以更改p
指向的内容。
这也意味着,“p”本身可以被修改,但“p”的内容不能被修改,所以*p = 10;
会产生错误。
一个例子将清楚的事情:
#include <stdio.h>
void foo(const int *p)
{
int x = 10;
p = &x; //legally OK
// *p = 20; <- Results in an error, cannot assign to a read-only location.
printf("%d\n",*p);
}
int main(int argc, char *argv[])
{
const int x10 = 100;
foo(&x10);
return 0;
}
要使上述程序根本不修改指针:
#include <stdio.h>
void foo(const int *const p)
{
int x = 10;
p = &x; //legally NOT OK, ERROR!
// *p = 20; <- Results in an error, cannot assign to a read-only location.
printf("%d\n",*p);
}
int main(int argc, char *argv[])
{
const int x10 = 100;
foo(&x10);
return 0;
}