关于增量运算符的优先级
Regarding priority of the increment operators
据我所知
int i = 10;
int j = 5;
j += ++i; //j = 16, i = 11 (first i increments and then adds to j)
和
int i = 10;
int j = 5;
j += i++; //j = 15, i = 11 (first i adds to j and then increments)
在Table5-4(运算符优先级和结合性)中的C in a nutshell中说后缀运算符++优先于一元运算符++,我不明白,相反的是我之前写的
The table
这是为什么?
运算符precedence/associativity 仅说明 C 代码应解析 的顺序。这与代码的执行方式无关1)。
意味着如果你有类似 *p++
的东西,它等同于 *(p++)
,因为后缀 ++ 优先于一元 *
。但是当稍后执行该代码时,内存位置 *p
将首先取消引用,然后 p
的地址增加 1 项。
这又是因为 postfix ++ 遵循的规则是 "the value computation of the result is sequenced before the side effect of updating the stored value of the operand"。
1) 考虑一个数学方程式,例如:a * b + c * d
- 数学中的运算符优先级和 C 迫使您将其计算为 (a * b) + (c * d)
但它没有告诉您是否应该在 c * d
.
之前或之后计算 a * b
据我所知
int i = 10;
int j = 5;
j += ++i; //j = 16, i = 11 (first i increments and then adds to j)
和
int i = 10;
int j = 5;
j += i++; //j = 15, i = 11 (first i adds to j and then increments)
在Table5-4(运算符优先级和结合性)中的C in a nutshell中说后缀运算符++优先于一元运算符++,我不明白,相反的是我之前写的
The table
这是为什么?
运算符precedence/associativity 仅说明 C 代码应解析 的顺序。这与代码的执行方式无关1)。
意味着如果你有类似 *p++
的东西,它等同于 *(p++)
,因为后缀 ++ 优先于一元 *
。但是当稍后执行该代码时,内存位置 *p
将首先取消引用,然后 p
的地址增加 1 项。
这又是因为 postfix ++ 遵循的规则是 "the value computation of the result is sequenced before the side effect of updating the stored value of the operand"。
1) 考虑一个数学方程式,例如:a * b + c * d
- 数学中的运算符优先级和 C 迫使您将其计算为 (a * b) + (c * d)
但它没有告诉您是否应该在 c * d
.
a * b