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

本文详细解析了C++中const与指针结合使用的四种情况:指向const的指针、const指针、指向const的const指针以及它们之间的区别与应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

指向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

转载于:https://www.cnblogs.com/zhuyf87/archive/2013/01/31/2887022.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值