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

后端 未结 8 1994
無奈伤痛
無奈伤痛 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:50

    Here we consider 4 types of pointers declarations:

    1. int * w; It means that w is a pointer to an integer type value. We can modify both the pointer and its content. If we initialize w while declaration as below: int * w = &a;
      Then, both of below operations are viable:
      w = &b;(true)
      *w = 1;(true)

    2. int * const x;
      It means x is a constant pointer that points to an integer type value. If we initialize x while declaration as below:
      int * const x = &a;
      Then, we cannot do: x = &b;(wrong) because x is a constant pointer and cannot be modified.
      However, it is possible to do: *x = 1;(true), because the content of x is not constant.

    3. int const * y; //both mean the same
      const int * y;
      It means that y is a pointer that points to a constant integer value. If we initialize y while declaration as below:
      int const * y = &a;
      Then, it is possible to do: y=&b;(true) because y is a non-constant pointer that can point to anywhere.
      However, we cannot do: *y=1;(wrong) because the variable that y points to is a constant variable and cannot be modified.

    4. int const * const z; //both mean the same
      const int * const z;
      It means that z is a constant pointer that points to a constant integer value. If we initialize z while declaration as below:
      int const * const z = &a;
      Therefore, non of below operations are viable:
      z = &b;(wrong)
      *z = 1;(wrong)

    0 讨论(0)
  • 2020-12-09 00:54

    int const * p; and const int * p are the same. It is when the const comes after the * that the semantics of the expression change.

    I know, it's crazy.

    0 讨论(0)
提交回复
热议问题