[C++] The meaning and difference between pointer constants and constant pointers

Simple memory method:

  • constis a constant, *is a pointer
  • *If it is before constand after, it is a pointer constant: * constthe address remains unchanged.
  • constBefore *and after, it is a constant pointer: const *the value does not change

Pointer to constant :指针指向的地址为常量

  • The memory address pointed to by a pointer constant is immutable.

  • When defining a pointer constant, it must be initialized and the value of the pointer cannot be modified ( that is, the pointer pointed to is immutable ).

  • Pointer constants allow you to modify the value of the object pointed to.

    Sample code:

    int value = 1;
    int* const ptr = &value;  // ptr是指针常量,指向value的地址
    
    *ptr = 100; 			  // 正确,可以通过指针常量修改value的值
     
    ptr = nullptr;            // 错误,无法修改指针常量指向的地址
    

Constant pointer :指针指向"常量"对象的地址

  • When defining a constant pointer, it does not need to be initialized, or it can be initialized later.

  • The constant pointer only requires that the value of the object cannot be modified through the pointer, but does not stipulate that the value of the object cannot be changed through other means.

  • The variable pointed to by a constant pointer is not necessarily a constconstant pointer. Declaring it as a constant pointer just means that the value pointed to the variable cannot be modified through the pointer. However, if the variable itself is not a constant, it can still be modified through other means .

  • Sample code:

    int value = 1;
    const int* ptr = &value;  // ptr是常量指针,指向value的地址
    int const* ptr = &value;  // 两种写法都可以
    
    *ptr = 100;               // 错误,不能通过常量指针修改value的值
    
    ptr = nullptr;            // 正确,可以修改常量指针的值,使其指向其他地址
    

constant pointer to constant:

  • Neither the value nor the address of the object pointed to by the pointer can be changed.

  • Sample code:

    int value = 1;
    const int* const ptr = &value;  //内容与地址均不可改变
    
    *ptr = 100;               // 错误,不能修改其值
    
    ptr = nullptr;            // 错误,不能修改其地址
    

If this article is helpful to you, I would like to receive a like from you!

Insert image description here

Guess you like

Origin blog.csdn.net/AAADiao/article/details/131141235