Common and simple understanding of constant pointers and pointer-to-pointer constants in C++

Constant pointer

  definition:

          Also called a constant pointer, it can be understood as a constant pointer, that is, this is a pointer, but it points to a constant. This constant is the value (address) of the pointer, not the value pointed to by the address.

     key point:

          1. The object pointed to by a constant pointer cannot be modified by this pointer, but it can still be modified by the original declaration;
          2. A constant pointer can be assigned to the address of a variable. The reason why it is called a constant pointer is to limit the modification of the variable through this pointer. Value;
          3. The pointer can also point to other places, because the pointer itself is just a variable and can point to any address;

 Code form:

         

 int const* p;  const int* p;

//-------常量指针-------
    const int *p1 = &a;
    a = 300;     //OK,仍然可以通过原来的声明修改值,
    //*p1 = 56;  //Error,*p1是const int的,不可修改,即常量指针不可修改其指向地址
    p1 = &b;     //OK,指针还可以指向别处,因为指针只是个变量,可以随意指向;

    //-------指针常量-------//
    int*  const p2 = &a;
    a = 500;     //OK,仍然可以通过原来的声明修改值,
    *p2 = 400;   //OK,指针是常量,指向的地址不可以变化,但是指向的地址所对应的内容可以变化
    //p2 = &b;     //Error,因为p2是const 指针,因此不能改变p2指向的内容
    
    //-------指向常量的常量指针-------//
    const int* const p3 = &a;
    //*p3 = 1;    //Error
    //p3 = &b;    //Error
    a = 5000;    //OK,仍然可以通过原来的声明修改值

So how to distinguish these types? The two const must be constant pointers to constants, it is easy to understand, mainly how to distinguish constant pointers and pointer constants:

Look at the  order of * and const , such as
     int const* p; //const * means constant pointer
     const int* p; //const * means constant pointer
     int* const p; //* const means pointer constant

 

In practical applications, constant pointers are used more than pointer constants. For example, constant pointers are often used in function parameter transfer to avoid internal modification of the function.

Guess you like

Origin blog.csdn.net/zl1107604962/article/details/90717368