有人可以解释我为什么下面的代码的结果是9? 我真的很困惑..
#include <stdio.h> int main (void) { int a = 3, rez; rez = a-- + (-3) * (-2); return 0; }Can someone please explain me why the result of the following code is 9? I am really confused..
#include <stdio.h> int main (void) { int a = 3, rez; rez = a-- + (-3) * (-2); return 0; }最满意答案
表达方式
rez = a-- + (-3) * (-2)被解析为
res = ((a--) + ((-3) * (-2)))并且被评价为“将( a-- )的结果添加到(-3) * (-2)的结果,并且最终结果被分配给res ”。
Postfix --具有比一元更高的优先级-其优先级高于二进制* ,其优先级高于二进制+ ,优先级高于二进制+ 。
注意, 评估的 优先顺序和顺序不是一回事 - 它不能保证a--在(-3) * (-2)之前被评估,或者-3在-2之前被评估; 所有这一切都得到保证, (-3) * (-2)的结果在被添加到a的结果之前是已知的。
此外,a的副作用不必在评估后立即应用。 这意味着以下是完全有效的操作顺序:
t1 = a t2 = -2 t2 = t2 * -3 res = t1 + t2 a = a - 1The expression
rez = a-- + (-3) * (-2)is parsed as
res = ((a--) + ((-3) * (-2)))and is evaluated as "the result of a-- is added to the result of (-3) * (-2), and the final result is assigned to res".
Postfix -- has higher precedence than unary -, which has higher precedence than binary *, which has higher precedence than binary +, which has higher precedence than =.
Note that precedence and order of evaluation are not the same thing - it's not guaranteed that a-- is evaluated before (-3) * (-2), or that -3 is evaluated before -2; all that's guaranteed is that the result of (-3) * (-2) is known before it can be added to the result of a--.
Futhermore, the side effect of a-- doesn't have to be applied immediately after evaluation. This means that the following is a perfectly valid order of operations:
t1 = a t2 = -2 t2 = t2 * -3 res = t1 + t2 a = a - 1更多推荐
发布评论