c++ - &++x 和 &x++ 的区别

标签 c++ post-increment pre-increment unary-operator postfix-operator

虽然这个问题可能在某处得到回答,但我找不到。

下面写的第一条语句有效而第二条语句无效?为什么?

int main() {
  int x = 1, y = 2;

  int *p = &++x; // First
  std::cout << "*p = " << *p << std::endl;

  // int *q = &x++; // Second
  // std::cout << "*q = " << *p << std::endl;
}

最佳答案

在本声明中

int *p = &++x;

使用了两个一元运算符:预增++ 和取地址。一元运算符从右到左执行。所以首先变量 x递增并将其地址分配给指针p,预递增运算符的结果为lvalue递增的对象。

所以例如这样的表达
++++x;

是正确的。

在本声明中
int *p = &x++;

使用了后缀运算符后增量++和取地址的一元运算符。后缀运算符相对于一元运算符具有更高的优先级。所以首先执行后增量。它的结果是一个临时对象,它在递增之前具有变量 x 的值。然后执行取地址操作。

但是,您可能无法获取临时对象的地址。所以对于这个声明,编译器会报错。

与预增量运算符相反,像这样的表达式
x++++;

是无效的。

来自 C++ 17 标准(5.3.2 递增和递减)

1 The operand of prefix ++ is modified by adding 1, or set to true if it is bool (this use is deprecated). The operand shall be a modifiable lvalue. The type of the operand shall be an arithmetic type or a pointer to a completely-defined object type. The result is the updated operand; it is an lvalue, and it is a bit-field if the operand is a bit-field....



和(5.2.6 增减)

1 The value of a postfix ++ expression is the value of its operand. [ Note: the value obtained is a copy of the original value — end note ]...



在 C 中,这两个操作都会产生一个值。所以在C中你也可能不会写
++++x;

关于c++ - &++x 和 &x++ 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61108409/

相关文章:

c++ - 确定集合迭代器的顺序

c - 指针递增和解引用(需要左值错误)

c++ - 混合运算符和表达式 new/delete

c++ - Mqtt 树莓派 C++

c++ - 非重叠连续子数组的最大长度和

c# - 如何在 foreach 和语句中递增整数?

c -++i 和 i++ 有什么区别?

c - s[++i] 之间的区别;和 s[i];++i;

c++ - iOS中Opencv人脸检测Cascade编译器报错

c - 为什么表达式 a==--a true 在 if 语句中?