区分“常量指针”和“指针常量”

指向const常量的指针(常量指针):关键字 const出现在*号左边,表示指针所指向的地址的内容是不可修改的,但是指针自身可变,也就是指针本身可以修改以指向其他内容。如:

const int * p1 = &i;
int const * p2 = &i;

const指针(指针常量):关键字const出现在*号右边,表示指针自身不可变,但其指向的地址的内容是可以修改的。如:

int * const p3 = &i;

指向const常量的const指针:指针自身不可修改,指针所指向的内容也不可以修改。如:

const int * const p4 = &i;
int const * const p5 = &i;

注意:指针常量必须在声明的同时对其初始化,不允许先声明一个指针常量随后再对其赋值,这和声明一般的常量是一样的。

示例代码:

int i = 0, j = 0;

// 指向const常量的指针(常量指针)
const int * p1 = &i;
int const * p2 = &i;

*p1 = 1; // error : 'p1' : you cannot assign to a variable that is const
*p2 = 1; // error : 'p2' : you cannot assign to a variable that is const

p1 = &j; // ok
p2 = &j; // ok

// const指针(指针常量)
int * const p3 = &i;

*p3 = 1; // ok
p3 = &j; // error : 'p3' : you cannot assign to a variable that is const

// 指向const常量的const指针
const int * const p4 = &i;
int const * const p5 = &i;

*p4 = 1; // error : 'p4' : you cannot assign to a variable that is const
*p5 = 1; // error : 'p5' : you cannot assign to a variable that is const
 
p4 = &j; // error : 'p4' : you cannot assign to a variable that is const
p5 = &j; // error : 'p5' : you cannot assign to a variable that is const

posted on 2013-01-31 14:50  zhuyf87  阅读(207)  评论(0编辑  收藏  举报

导航