Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/136.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;优先性和结合性_C++_Pointers_Computer Science_Operator Precedence - Fatal编程技术网

C++ C++;优先性和结合性

C++ C++;优先性和结合性,c++,pointers,computer-science,operator-precedence,C++,Pointers,Computer Science,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++; 由于*和++具有相同的优先级,那么关联性是从右到左的,我们是否应该首先应用++操作符,即先增加指针,然后再*(取消引用)它 因此相应地,score\u ptr将增加到1004,然后取消对它的引用将给出分数的第二个元素,

这段代码:

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++;
由于
*
++
具有相同的优先级,那么关联性是从右到左的,我们是否应该首先应用
++
操作符,即先增加指针,然后再
*
(取消引用)它

因此相应地,
score\u ptr
将增加到
1004
,然后取消对它的引用将给出分数的第二个元素,即
2


如何以及为什么这会给我
1
而不是
2
的输出?

增量将首先发生,它具有更高的优先级,它相当于
*(score_ptr++)
,但它是一个后增量,这意味着它只会在使用取消引用的指针后发生,即表达式达到

如果你使用

std::cout << *++score_ptr;
std::cout
与
*
++
具有相同的优先级

否,后缀
运算符+++
大于
运算符*
;然后,
*score\u ptr++
相当于
*(score\u ptr++)
。请注意,将递增操作数并返回原始值,然后
*(score_ptr++)
将给出值
1

结果是操作数原始值的prvalue副本


另一方面,前缀
operator++
返回递增的值。如果将代码更改为
*++score\u ptr
(相当于
*(++score\u ptr)
),则结果将是
2
(这可能是您所期望的)。

@Ranoiaetep Fine.)术语“关联性”有一个问题。它只在C++ 17标准中使用过一次,在注释中描述了如何解析表达式。诸如
*score_ptr++
等表达式的计算规则不属于标准中的语法结果。优先级和关联性“规则”(在语言的非正式描述中使用)就是从这些规则中派生出来的,并不一定告诉您实际的规则是什么。
std::cout << *++score_ptr;