What's the point of const pointers?

后端 未结 17 1915
粉色の甜心
粉色の甜心 2020-11-30 17:28

I\'m not talking about pointers to const values, but const pointers themselves.

I\'m learning C and C++ beyond the very basic stuff and just until today I realized t

17条回答
  •  生来不讨喜
    2020-11-30 17:34

    int iVal = 10; int *const ipPtr = &iVal;

    Just like a normal const variable, a const pointer must be initialized to a value upon declaration, and its value can not be changed.

    This means a const pointer will always point to the same value. In the above case, ipPtr will always point to the address of iVal. However, because the value being pointed to is still non-const, it is possible to change the value being pointed to via dereferencing the pointer:

    *ipPtr = 6; // allowed, since pnPtr points to a non-const int

提交回复
热议问题