【问题标题】:Order of execution in "IF" statement when multiple conditions present [duplicate]存在多个条件时“IF”语句中的执行顺序[重复]
【发布时间】:2015-03-04 01:37:56
【问题描述】:

我必须使用 if 语句检查 3 种方法的结果。如果method1为真,那么我只需要调用method2,如果method2为真,那么我只需要调用method3。目前我正在为此目的使用以下代码。

if(method1())
{
    if(method2())
    {
        if(method3())
        {
            cout << "succeeded";
        }
        else
        {
            cout << "failed";
        }
    }
    else
    {
        cout << "failed";
    }
}
else
{
    cout << "failed";
}

我只想使用一个 if 语句并在其中调用所有 3 个方法。所以我正在考虑以下方式。下面的代码和上面的代码是一样的还是会有所不同?

if(method1() && method2() && method3())
{
    cout << "succeeded";
}
else
{
    cout << "failed";
}

【问题讨论】:

  • 是的,&amp;&amp; 使用短路(假设 method 不返回 operator &amp;&amp; 重载的对象)。

标签: c++ if-statement short-circuiting


【解决方案1】:

结果将是相同的,因为&amp;&amp; 是一个短路运算符。这意味着如果第一个操作数的计算结果为 false,则不会计算第二个操作数。

【讨论】:

    猜你喜欢
    • 2013-05-18
    • 1970-01-01
    • 1970-01-01
    • 2022-12-31
    • 1970-01-01
    • 2012-09-02
    • 1970-01-01
    • 2016-12-13
    • 2011-01-28
    相关资源
    最近更新 更多