StoryTeller 已经在标准中解释了为什么对于您的示例,表达式(i)
仍然是左值,但我相信您无缘无故地挂在规范上,所以请允许我尝试解决您的问题。
我检查了代码和规则,发现:在赋值表达式语义中:
赋值运算符应具有可修改的左值作为其左操作数。
赋值表达式在赋值后具有左操作数的值,但不是左值。
整个引用是指整个赋值表达式,而不是 lhs 或 rhs。
“赋值运算符应有一个可修改的左值作为其左操作数。” 声明 lhs 必须是可修改的左值。
“赋值表达式在赋值后具有左操作数的值,但不是左值。” 声明整个赋值表达式本身作为结果具有 lhs 的值,并且本身是一个右值。
所以以下都是真的:
int i;
i <- modifiable lvalue
(i) = 1;
(i) <- modifiable lvalue (per StoryTeller's answer)
1 <- rvalue
((i) = 1) <- rvalue
为什么这很重要?考虑以下:
int i = 0, j = 0, k = 0;
i = j = k = 1;
// parsed as `i = (j = (k = 1))`
// the expression `k = 1` has the value `1` and is an rvalue
// the expression `j = (k = 1)` has the value `1` and is an rvalue
(i = 2) = 3;
// is invalid, the expression `i = 2` is an rvalue, but it may not be the lhs of the assignment
就我而言,有两个赋值表达式:括号中的(i) = 1
和i
。所以(i)
应该是一个右值。
不,这是不正确的。(i) = 1
是唯一的赋值表达式。有两个子表达式(一个带括号的标识符(i)
和一个数字常量1
)。