当const, int遇到*

本文介绍了C++中const关键字在指针声明时的不同用法,解释了constint*p和intconst*p的区别,以及它们如何限制对指针所指向内容的修改。constint*p不允许修改指针内容,而int*constp则保护指针本身不被改变。示例代码展示了这些约束在实践中的应用和编译错误情况。
摘要由CSDN通过智能技术生成

函数接口定义时常常遇到的是const int p或者int const p,目的让编译器帮助程序员在该函数的编写过程中不要通过p来修改p所执行的内容。如果尝试修改,编译会报错“assignment of read-only location”提示你在对一个只读区域进行赋值。原因是取值运算符的结合方向是从右到左,在左边的是对*p的修饰,说明其中的内存是const int或者int const的。
还有一种不是那么常见的定义int *const p,根据右结合性,p是const的,也就是说在后续使用p时不能对它进行修改的。如果尝试通过p=a的方式尝试把int *a传递给p,编译器会报错“assignment of read-only variable”,提示你正在对一个只读变量进行赋值操作。

#include <stdio.h>

int main(int argc, char *argv[])
{
    int a[] = {10, 20, 30, 40, 50, 60};
    int b[] = {1, 2, 3, 4, 5, 6};
    
    const int *p_not_change_value = a; 
    int * const p_not_change_pointer = a;

    int const *p_test = a;
    //*p_test = 20;  //fail to compile:  assignment of read-only location
    p_test = b;
    
    //*p_not_change_value = 100;  //fail to compile: assignment of read-only location
    p_not_change_value = b;
    *p_not_change_pointer = 100;
    //p_not_change_pointer = b; //fail to compile: assignment of read-only variable
    printf("*p_not_change_value:%d *p_not_change_pointer:%d\n", *p_not_change_value, *p_not_change_pointer);
    #endif
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值