3 minutes to learn the priority of C++ increment decrement operator and dereference operator

The prefix ++, – operator precedence is equal to the dereference operator *, right-to-left associative

int main() {
    
    

  array<int, 5> ai={
    
    1,2,3,4,5};
  int* p = &ai[0];

  //2
  cout << *++p << endl;//将指针p指向的地址+1后再解引用(指针指向ai[1]的地址)
  return 0;
}
int main() {
    
    

  array<int, 5> ai={
    
    1,2,3,4,5};
  int* p = &ai[0];

  //2
  cout << ++*p << endl;//解引用后得到ai[0]的值(1),再将值+1(指针依然指向ai[0]的地址)
  return 0;

The suffix ++ and – operators have higher priority than the dereference operator *, so the two operators are combined from left to right . If you don’t understand this sentence, you can see the following example

int main() {
    
    

  array<int, 5> ai={
    
    1,2,3,4,5};
  int* p = &ai[0];

  //1
  cout << *p++ << endl;
  //由于++是后缀的,所以先解引用p(从左向右结合),
  //由于后缀++优先级高于*,最后将++运算符用于p而不是*p,
  //输出1之后将指针p指向数值第二个元素ai[1]的地址。
  return 0;
int main() {
    
    

  array<int, 5> ai={
    
    1,2,3,4,5};
  int* p = &ai[0];

  //2
  cout << (*p)++ << endl;//()加持,先解引用后再将值+1(指针依然指向ai[0]的地址)
  return 0;

Guess you like

Origin blog.csdn.net/baidu_38495508/article/details/122408385