虽然这个问题可能在某处得到回答,但我找不到。
下面写的第一条语句有效而第二条语句无效?为什么?
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/