ill*_*lla 2 c++ computer-science pointers operator-precedence
这段代码:
int scores[] {1,2,3,4};
int *score_ptr {scores};
//let's say that initial value of score_ptr is 1000
std::cout<<*score_ptr++;
Run Code Online (Sandbox Code Playgroud)
产生输出:
1
Run Code Online (Sandbox Code Playgroud)
As*和++具有相同的优先级,然后结合性是从右到左,我们不应该++先应用运算符,即先增加指针然后*(取消引用)它吗?
因此,相应地score_ptr将增加到1004然后取消引用它将给出分数的第二个元素,即2.
这如何以及为什么给我输出1而不是2?
由于
*与++具有相同的优先级
不,后缀operator++具有更高的优先级比operator*; 那么*score_ptr++相当于*(score_ptr++). 请注意,后缀operator++将增加操作数并返回原始值,然后*(score_ptr++)给出值1。
结果是操作数原始值的纯右值副本。
另一方面,前缀operator++返回递增的值。如果您将代码更改为*++score_ptr(相当于*(++score_ptr)),那么结果将是2(这可能是您所期望的)。