Can the C compiler optimizer violate short-circuiting and reorder memory accesses for operands in a logical-AND expression?

后端 未结 4 1775
傲寒
傲寒 2021-01-18 04:50

We know that logical-AND operator (&&) guarantees left-to-right evaluation.

But I am wondering if the compiler optimizer can ever reorder the me

4条回答
  •  既然无缘
    2021-01-18 05:32

    According to the C11 ISO standard, at §C, annex C, it's stated that

    The following are the sequence points described in ... Between the evaluations of the first and second operands of the following operators: logical AND && (6.5.13); logical OR || (6.5.14); comma , (6.5.17).

    And, as stated in §5.1.2.3:

    Sequenced before is an asymmetric, transitive, pair-wise relation between evaluations executed by a single thread, which induces a partial order among those evaluations. Given any two evaluations A and B, if A is sequenced before B, then the execution of A shall precede the execution of B.

    So it's guaranteed that the first operand is evaluated before the second. No safe optimization should be possible in this circumstance.

提交回复
热议问题