C编译器优化和短路评估

前端之家收集整理的这篇文章主要介绍了C编译器优化和短路评估前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
参见英文答案 > Is short-circuiting logical operators mandated? And evaluation order?7个
这是我的代码
b = f() || b;

函数f()有副作用,必须始终执行.通常,只有正确的操作数可以短路,这个代码应该可以工作.但是我担心一些编译器会反转两个操作数,因为短路功能评估而不是简单的变量评估会更有效.我知道g -O3可以破坏一些规范,但我不知道这个代码是否会受到影响.

那么,我的代码是否没有风险?

我知道Is short-circuiting logical operators mandated? And evaluation order?,但我的问题是关于编译器优化,我不知道他们不能打破标准(即使这会很奇怪).

解决方法

But I am afraid some compilators reverse the two operands

必须从左到右评估这些表达式.关于运算符&&,||,?和,以及.他们特别提到了顺序,以及强制序列点.

§5.14.1(逻辑AND)

The && operator groups left-to-right. The operands are both contextually converted to bool (Clause 4). The result is true if both operands are true and false otherwise. Unlike &,&& guarantees left-to-right evaluation: the second operand is not evaluated if the first operand is false.

§5.15.1(逻辑或)

The || operator groups left-to-right. The operands are both contextually converted to bool (Clause 4). It returns true if either of its operands is true,and false otherwise. Unlike |,|| guarantees left-to-right evaluation; moreover,the second operand is not evaluated if the first operand evaluates to true.

§5.16.1(条件运算符)

Conditional expressions group right-to-left. The first expression is contextually converted to bool (Clause 4). It is evaluated and if it is true,the result of the conditional expression is the value of the second expression,
otherwise that of the third expression. Only one of the second and third expressions is evaluated. Every value computation and side effect associated with the first expression is sequenced before every value computation
and side effect associated with the second or third expression.

§5.19.1(逗号运算符)

The comma operator groups left-to-right. A pair of expressions separated by a comma is evaluated left-to-right; the left expression is a discarded value
expression (Clause 5). Every value computation and side effect associated with the left expression is sequenced before every value computation and side effect associated with the right expression. The type and value of the result are the type and value of the right operand; the result is of the same value category
as its right operand,and is a bit-field if its right operand is a glvalue and a bit-field. If the value of the right operand is a temporary (12.2),the result is that temporary.

关于您对违反此订单的优化的担忧,不允许编译器更改订单.编译器必须首先(尝试)遵循该标准.然后他们可以尝试让您的代码更快.它们可能不会仅仅为了性能而违反标准.这破坏了制定标准的整个前提.

猜你在找的C&C++相关文章