C++ 优化 If 语句

标签 c++ optimization

考虑以下语句:

 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
  1. The && operator groups left-to-right. The operands are both implicitly converted to type 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.

|| 运算符的规则类似:

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
  1. The || operator groups left-to-right. The operands are both implicitly 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.

还有条件 ? 运算符:

ISO/IEC C++ Standard 14882 §5.16 Conditional operator [expr.cond] conditional-expression: logical-or-expression logical-or-expression ? expression : assignment-expression

  1. Conditional expressions group right-to-left. The first expression is implicitly 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. 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/

相关文章:

arrays - 排序数组和查找更改 - Swift

c++ - C++11 标准是否正式定义了获取、释放和消费操作?

c++ - DXGI 桌面重复 : encoding frames to send them over the network

sql-server - 如何修复在缓存之前运行缓慢的查询

c# - .Net优化

java - 我可以在 String.format 中预编译格式字符串吗? (或者做任何其他事情来更快地格式化日志?)

sql - PostgreSQL 优化 : running select queries on preselected subset

c++ - 在 C++ 项目之间共享中间文件?

java - Android 中的位图和 OpenCV 中的 Mat

c++ - 在 C++ 中修改 const int