gpt4 book ai didi

c - 表达式中的括号是否先于其他任何内容求值?

转载 作者:太空宇宙 更新时间:2023-11-04 05:19:36 24 4
gpt4 key购买 nike

在 C 中,操作数的计算顺序与运算符优先级和结合性无关。

假设我在 C 中有一个表达式:expr1 * expr2 + (expr3 + expr4) (中间没有序列点)

When this expression is evaluated then:

  1. Will sub-expressions expr3 and expr4 be evaluated before expr1 and expr2 because of the parenthesis?

  2. Or does the parenthesis ensure that operators inside the parenthesis are evaluated before the operators outside the parenthesis?

Do the parentheses ensure order of evaluation of operands or operators?

最佳答案

摘自2011年语言标准在线草案:

6.5 Expressions
...
3 The grouping of operators and operands is indicated by the syntax. 85) Except as specified later, side effects and value computations of subexpressions are unsequenced. 86)
85) The syntax specifies the precedence of operators in the evaluation of an expression, which is the same as the order of the major subclauses of this subclause, highest precedence first. Thus, for example, the expressions allowed as the operands of the binary + operator (6.5.6) are those expressions defined in6.5.1 through 6.5.6. The exceptions are cast expressions (6.5.4) as operands of unary operators(6.5.3), and an operand contained between any of the following pairs of operators: groupingparentheses () (6.5.1), subscripting brackets [] (6.5.2.1), function-call parentheses () (6.5.2.2), andthe conditional operator ? : (6.5.15).Within each major subclause, the operators have the same precedence. Left- or right-associativity isindicated in each subclause by the syntax for the expressions discussed therein.

86) In an expression that is evaluated more than once during the execution of a program, unsequenced andindeterminately sequenced evaluations of its subexpressions need not be performed consistently indifferent evaluations.

清澈如泥,对吧?它的意思是,给定一个像

这样的表达式
x = a++ + b++ * (--c / ++d)

每个子表达式 a++b++--c++d 都可以求值以任何顺序;仅仅因为 --c++d 由括号分组并不意味着它们首先被评估。此外,每个 ++-- 的副作用不必在计算表达式后立即应用。

所有运算符优先级保证是 --c/++d结果 将乘以 b++ 的结果,并且a++ 的结果将添加到该值;它不保证任何表达式在任何其他表达式之前被求值

密切注意脚注 86;如果上面的表达式出现在循环中,则没有理由期望每次循环中子表达式都以相同的顺序求值。实际上,它们很可能会,但是编译器被明确赋予了改变一切的自由。

由于可以自由地评估表达式并以任何顺序应用副作用,某些表达式如 a++ + a++ 不会给出一致的结果;标准明确地将其称为未定义行为,这意味着编译器没有义务以任何特定方式处理这种情况。它可以忽略该问题,它可以发出警告,它可以因错误而停止翻译等等,但是没有要求它做任何一件特定的事情。

关于c - 表达式中的括号是否先于其他任何内容求值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17402853/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com