const And pointer

本文介绍了C/C++中const和pointer结合使用的情况,包括const int*、int const*、int* const以及const int* const四种组合的含义。文章通过实例说明了这些组合分别表示的指针和所指变量的可变性,并提供了相应的测试代码进行验证。

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

const And pointer



概述

pointer (指针):用于指向存储某一数据类型变量的内存空间

const:赋予变量或者对象只读属性

现以int数据类型为例,const与pointer的组合有一下几种情况

  1. const int* p;
  2. int const* p;
  3. int* const p;
  4. const int* const p;
  5. int const* const p;

其中
  情况1情况2等价,表示一个指向整型常量的指针,不能修改整型常量的值 —— p is a pointer pointing to a const int(int const)

  情况3,表示一个常量指针,指向整型变量,即一旦指针指向某一个整型变量之后,不能指向其他任意一个整型变量 —— p is a const pointer pointing to a int

  情况4和情况5等价,表示一个常量指针,指向整型常量,即同时拥有情况1/2情况3的特点 —— p is a const pointer pointing to a const int(int const)


图示

情况1情况2
const int* p; or int const* p;

情况3
int* const p;

情况4情况5
const int* const p; or int const* const p;


测试代码

#include <iostream>

using namespace std;

void constAndPointer()
{
    int data1 = 100;
    int data2 = 400;

    // const int* p | int const* p
    const int* p1 = &data1;
    int const* p2 = &data1;

    //*p1 = 200;  // error
    //*p2 = 200;  // error
    // end -------------------------

    // int* const p
    int* const p3 = &data1;

    cout << "original value : " << data1 << endl;
    *p3 = 200;
    cout << "after modifying : " << data1 << endl;

    //p3 = &data2;  // error    
    // end -------------------------

    // const int* const p | int const * const p
    const int* const p4 = &data1;
    int const* const p5 = &data1;

    //*p4 = 200;  // error
    //*p5 = 200;  // error
    //p4 = &data2;  // error
    //p5 = &data2;  // error
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值