about “int const *p” and “const int *p ”

后端 未结 8 2002
無奈伤痛
無奈伤痛 2020-12-09 00:11
#include 
using namespace std;

int main(int argc, char* argv[])
{
    int i1 = 0;
    int i2 = 10;

    const int *p = &i1;
    int const *p2 =          


        
8条回答
  •  一向
    一向 (楼主)
    2020-12-09 00:44

    No, the const keyword before the * means that the variable you are pointing to is a "const" variable and only it can not be modified.

    1. If you want a pointer that can't be reassigned then you need to declare it as Foo* const p = &bar;
    2. If you want a pointer that points to a "const" object that can't be reassigned declare it as const Foo* const p = &bar

    It is perfectly fine to have a pointer of const int* foo be assigned to a pointer of const int* const bar just like it is fine to have an int's value assigned to a const int. Think of it in the same manner.

提交回复
热议问题