我总是搞砸如何正确使用const int*、const int*const和int const*。有没有一套规则来定义你能做什么和不能做什么?

我想知道在赋值、传递给函数等方面的所有注意事项。


当前回答

两边带有int的常量将使指针指向常量int:

const int *ptr=&i;

or:

int const *ptr=&i;

*后的const将使常量指针指向int:

int *const ptr=&i;

在这种情况下,所有这些都是指向常量整数的指针,但没有一个是常量指针:

 const int *ptr1=&i, *ptr2=&j;

在这种情况下,所有指针都指向常量整数,ptr2是指向常量整数的常量指针。但ptr1不是常量指针:

int const *ptr1=&i, *const ptr2=&j;

其他回答

就像每个人都指出的那样:

常量X*p、X*constp和常量X*const p之间有什么区别?

必须读取指针声明从右到左。const X*p表示“p指向常量的X”:X对象不能通过p更改。X*const p表示“p是指向非常量X的常量指针”:不能更改指针p本身,但可以通过p更改X对象。const X*const p表示“p是指向常量X的常量指针”:不能更改指针p本身,也不能通过p更改X对象。

对我来说,常量的位置,即它相对于*是出现在左侧还是右侧,还是同时出现在左侧和右侧,有助于我理解实际含义。

*左边的常量表示指针指向的对象是常量对象。*右边的常量表示指针是常量指针。

下表摘自斯坦福CS106L标准C++编程实验室课程阅读器。

反向阅读(由顺时针/螺旋法则驱动):

int*-指向int的指针int const*-指向const int的指针int*const-指向int的const指针int const*const-指向const int的const指针

现在,第一个常量可以位于类型的任一侧,因此:

常量int*==int常量*const int*const==int const*const

如果你想变得疯狂,你可以这样做:

int**-指向int指针的指针int**const-指向int指针的const指针int*const*-指向int的const指针int const**-指向常量int的指针int*const*const-指向int的常量指针的常量指针...

为了确保我们清楚const的含义:

int a = 5, b = 10, c = 15;

const int* foo;     // pointer to constant int.
foo = &a;           // assignment to where foo points to.

/* dummy statement*/
*foo = 6;           // the value of a can´t get changed through the pointer.

foo = &b;           // the pointer foo can be changed.



int *const bar = &c;  // constant pointer to int 
                      // note, you actually need to set the pointer 
                      // here because you can't change it later ;)

*bar = 16;            // the value of c can be changed through the pointer.    

/* dummy statement*/
bar = &a;             // not possible because bar is a constant pointer.           

foo是指向常量整数的变量指针。这允许您更改指向的内容,但不更改指向的值。最常见的情况是,C样式字符串中有一个指向常量字符的指针。您可以更改指向的字符串,但不能更改这些字符串的内容。当字符串本身位于程序的数据段中且不应更改时,这一点很重要。

bar是指向可更改值的常量或固定指针。这就像没有额外语法糖的引用。由于这一事实,通常您会在使用T*常量指针的地方使用引用,除非您需要允许NULL指针。

两边带有int的常量将使指针指向常量int:

const int *ptr=&i;

or:

int const *ptr=&i;

*后的const将使常量指针指向int:

int *const ptr=&i;

在这种情况下,所有这些都是指向常量整数的指针,但没有一个是常量指针:

 const int *ptr1=&i, *ptr2=&j;

在这种情况下,所有指针都指向常量整数,ptr2是指向常量整数的常量指针。但ptr1不是常量指针:

int const *ptr1=&i, *const ptr2=&j;

对于那些不了解顺时针/螺旋规律的人:从变量的名称开始,顺时针移动(在这种情况下,向后移动)到下一个指针或类型。重复此操作,直到表达式结束。

下面是一个演示: