简体   繁体   中英

Pointers and const in C++

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?

The const in the second example applies to the int , ie you have a non- const pointer to a const int . Since types in C and C++ are read right to left, it is actually easiest to put the const always to right. It is also the only place where it can be put consistently:

int i(0);
int      *       p0(&i); // non-const pointer to non-const int
int const*       p1(&i); // non-const pointer to const int
int      * const p2(&i); // const pointer to non-const int
int const* const p3(&i); // const pointer to const int

That is, you can apply const to the pointer ( p0 and p1 can be changed but p2 and p3 cannot) as well as to the entity the pointer points to ( *p0 and *p2 can be changed but *p1 and *p3 cannot be changed). For the second and the forth line, you could swap the int and the const but I'd advise against do so.

In C even integer is not constant but we are declaring our pointer as we are dealing with the constant integer. in this case C implicitly convert that integer to constant when assigning it reference to pointer.

Usually we do this when passing some values to function where we can avoid some unexpected change.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM