Search code examples
c++if-statementshort-circuiting

Order of execution in "IF" statement when multiple conditions present


I have to check the outcome of 3 methods using if statement. if method1 is true then only i need to call method2 and if method2 is true then only i need to call method3. Currently I am using the following code for this purpose.

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

I want to use only one if statement and call all 3 methods inside it. So I am thinking the following way. Will the below code works same as above code or will it be different?

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

Solution

  • The result will be the same, because && is a short-circuiting operator. This means that if the first operand evaluates to false, the second operand will not be evaluated.