2

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?

4

2 回答 2

5

第二const个示例中的 the 应用于int,即您有一个指向 a 的非const指针const intconst由于 C 和 C++ 中的类型是从右到左读取的,因此将always放在右边实际上是最简单的。它也是唯一可以一致放置的地方:

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

也就是说,您可以应用于const指针(p0并且p1可以更改但不能更改)p2以及p3指针指向的实体(*p0并且*p2可以更改但*p1不能*p3更改)。对于第二行和第四行,您可以交换 theint和 theconst但我建议不要这样做。

于 2013-11-14T01:43:42.280 回答
0

在 C 中,偶数不是常量,但我们在处理常量整数时声明了指针。在这种情况下,C 在将其引用分配给指针时将该整数隐式转换为常量。

通常我们在将一些值传递给函数时这样做,我们可以避免一些意外的变化。

于 2013-12-16T12:47:09.837 回答