简体   繁体   English

这个带括号和不带括号的 C++ 代码有什么区别?

[英]What is the difference for this C++ code with and without the parentheses?

What is the purpose of the parentheses in the following piece of code?以下代码段中括号的用途是什么? What would be happening if the parentheses were not there?如果没有括号会发生什么? Sorry, I am new to C++.抱歉,我是 C++ 新手。

void foo(int * xPtr) {
  (*xPtr)++;
}

使用括号,您增加指针引用的对象,没有它们,您增加指向下一个内存地址的指针,然后取消引用它(在这种情况下什么都不做)。

If parentheses are not there then you are basically modifying the memory address stored inside xPtr and then dereferencing the pointer.如果没有括号,那么您基本上是在修改存储在xPtr的内存地址,然后取消引用指针。 So clearly this is not what is desired.很明显,这不是我们想要的。

Say we want the value stored at memory location 1000 to be incremented, but假设我们希望存储在内存位置1000的值递增,但是

*xPtr++;

results in incrementing the memory location by 4 and then,value at memory location 1004 is accessed, assuming size of integer on the machine is 4 bytes .导致内存位置增加 4,然后访问内存位置1004处的值,假设机器上的整数大小为4 bytes

(*xPtr)++ will increment the thing xPtr points to. (*xPtr)++将增加xPtr指向的东西。

Postfix ++ has higher precedence than unary * ; Postfix ++优先级高于一元* without parentheses, the code would be parsed as *(xPtr++) - you're incrementing xPtr , not the thing xPtr points to.如果没有括号,代码将被解析为*(xPtr++) - 您正在增加xPtr ,而不是xPtr指向的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM