考虑以下语句:
C a, b; //C contains c1, c2 and c3 all integers
if(a.c1==b.c1 && a.c2 == b.c2) {
a.c3=b.c3;
}
此语句是否会针对以下内容进行优化:
if(a.c1 == b.c1) {
if(a.c2 == b.c2) {
a.c3=b.c3;
}
}
据我所知,C++ 编译器不会执行这种操作,因为它可能有副作用。但这些是内置类型。
- 标准中有什么相关内容吗?
- 如果它是特定于编译器的,那么主流编译器(MS、GNU、Intel)是否正在这样做?
最佳答案
是的。以下代码片段:
C a, b; //C contains c1, c2 and c3 all integers
if(a.c1==b.c1 && a.c2 == b.c2)
{
a.c3=b.c3;
}
将为此“优化”(或类似的东西):
if(a.c1 == b.c1)
{
if(a.c2 == b.c2)
{
a.c3=b.c3
}
}
这是必需的,不是因为优化,而是因为 C++ 标准要求 short-circuit evaluation .因此,合理地符合标准的 C++ 编译器应该能够将其短路。
C++ 标准中没有一个地方明确声明某些 bool 运算符是短路的。规则暗示:
ISO/IEC C++ Standard 14882 §5.14 Logical AND operator [expr.log.and]
logical-and-expression: inclusive-or-expression logical-and-expression && inclusive-or-expression
- The
&&
operator groups left-to-right. The operands are both implicitly converted to typebool
(clause 4). The result istrue
if both operands aretrue
andfalse
otherwise. Unlike&
,&&
guarantees left-to-right evaluation: the second operand is not evaluated if the first operand isfalse
.
||
运算符的规则类似:
ISO/IEC C++ Standard 14882 §5.15 Logical OR operator [expr.log.or]
logical-or-expression: logical-and-expression logical-or-expression || logical-and-expression
- The
||
operator groups left-to-right. The operands are both implicitly converted tobool
(clause 4). It returnstrue
if either of its operands istrue
, andfalse
otherwise. Unlike|
,||
guarantees left-to-right evaluation; moreover, the second operand is not evaluated if the first operand evaluates totrue
.
还有条件 ?
运算符:
ISO/IEC C++ Standard 14882 §5.16 Conditional operator [expr.cond] conditional-expression: logical-or-expression logical-or-expression ? expression : assignment-expression
- Conditional expressions group right-to-left. The first expression is implicitly converted to
bool
(clause 4). It is evaluated and if it istrue
, the result of the conditional expression is the value of the second expression, otherwise that of the third expression. All side effects of the first expression except for destruction of temporaries (12.2) happen before the second or third expression is evaluated. Only one of the second and third expressions is evaluated.
关于C++ 优化 If 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6801844/