c++ 常量指针和指针常量

常量指针:

  • const在*之前
  • 指针的地址是可以被再次赋值的(可以修改的)
  • 指针地址上面的值(变量)是不能被修改的
  • 常量指针的常量是不能被改变的

指针常量:

  • const在*之后
  • 指针的地址是不可以被再次赋值的(不可以修改的)
  • 指针地址上面的值(变量)是能被修改的
  • 指针常量的指针地址是不能被改变的

 

    int num = 5;
    int num2 = 10;
    int num3 = 2;
    // 常量指针,constant pointer, (keyword const before *)
    const int *i_ptr = #
    //can change the address of i_ptr pointed to
    i_ptr = &num2;
    //but cannot change it value
    //*i_ptr = 90;
    cout << "i_ptr value: " << *i_ptr << endl;

    // 指针常量,pointer constant, (keyword const after *)
    int *const i_prt2 = &num3;
    //cannot change the address of i_prt2 pointed to
    //&i_prt2 = &num2;
    //but can change it value
    *i_prt2 = 300;
    cout << "i_prt2 value: " << *i_prt2 << endl;

 

i_ptr value: 10
i_prt2 value: 300

 

posted @ 2023-01-11 01:09  johnny_zhao  阅读(12)  评论(0编辑  收藏  举报