1

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";
}
Jarod42
  • 203,559
  • 14
  • 181
  • 302
Arun
  • 2,247
  • 3
  • 28
  • 51
  • Yes, `&&` use short-circuit (assuming `method` doesn't return object with `operator &&` overloaded). – Jarod42 Jan 06 '15 at 11:36

1 Answers1

3

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.

TartanLlama
  • 63,752
  • 13
  • 157
  • 193