When dealing with pointers and const, I see there are three ways to declare them:
1)
int nValue = 5; int *const pnPtr = &nValue; 2)
int nValue = 5; const int *pnPtr = &nValue; 3)
const int 5; const int *const pnPtr = &nValue; Example 1 is referred to as "Const pointer to non-const". The address cannot change but the value can change. So we can do something like the following, since nValue in example 1 is a non-const int:
int nValue = 5; int const *pnPtr = &nValue; *pnPtr = 6; But we cannot do the following in example 1:
int nValue = 5; int nValue2 = 6; int const *pnPtr = &nValue; pnPtr = &nValue2; Example 2 is referred to as "Pointer to const". This means that the address can change, but the value cannot. We can do the following:
int nValue = 5; int nValue2 = 6; const int *pnPtr = &nValue; pnPtr = &nValue2; But we cannot do the following in Example 2:
int nValue = 5; int nValue2 = 6; const int *pnPtr = &nValue; *pnPtr = nValue2; Example 3 is a "Const pointer to const". This means neither address or value can change:
const int nValue; const int *const pnPtr = &nValue; My question is related to the second example. Why is the second example called a " Pointer to const" when nValue is not a const. It is a regular int declaration. Also, in the second example, what if when we assign it another address, that other address has a different value, can't we just deference that address, and therefore return the different value? Wouldn't that defeat the whole purpose?