C的操作顺序?(C order of operations?)

系统教程 行业动态 更新时间:2024-06-14 16:59:22
C的操作顺序?(C order of operations?)

有人可以解释我为什么下面的代码的结果是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 - 1

The 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

更多推荐

本文发布于:2023-04-16 19:09:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/bf9ce1cdcb852c94a5d5ae83be6a721b.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:顺序   操作   operations   order

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!