c++function

Alternatives to using boolean variable to enable next step of program to progress (without early return)


I have several steps in a function, if a step fails, I don't want to execute the following steps. I also would like to only have one return statement. one option is nested if-else but that gets nasty so I won't even put an example here.

What I've been doing is something like this (assume step_n functions return bool):

bool my_function()
{
   bool succeeded;

   succeeded = step_1();

   if(succeeded)
   {
      succeeded = step_2();
   }

   if(succeeded)
   {
      succeeded = step_3();
   }

   ...

   if(succeeded)
   {
      succeeded = step_n();
   }

   return succeeded;
}

This seems like the best case I can think of, but when the function does not return bool and I have to do an additional check each function call, things can get very repetitive and ugly.

Any modern c++ ways to accomplish this same idea?


Solution

  • The && operator will short-circuit, meaning that if the left operand produces false, the right operand is not evaluated, since it will not change the result.

    This code is equivalent to what you show.

    bool my_function()
    {
       return step_1() &&
              step_2() &&
              step_3() &&
       ... 
              step_n();
    }
    

    It's not "modern" though. Any version of C++ can do this.