Search code examples
c++refactoringgoto

Refactor code without goto


I'm little confused. How this statement can be refactored without goto?

if(first_expression)
{
    // ....
    if(second_expression)
    {
        // ....
    }
    else
    {
        goto jump_out;
    }
}
else
{
    jump_out:
    // ....
}

Is this good way?

bool expressionFailed = false;
if(first_expression)
{
    if(second_expression)
    {
        // ....
    }
    else
        expressionsFailed = true;
}
else
    expressionsFailed = true;

if(expressionsFailed)
{
    // ....
}

I can not use &&, because code after if(first_expression) need to be executed when second_expression = false


Solution

  • You are on the right track. I would simplify it to:

    bool succeeded = false;
    if(first_expression)
    {
        if(second_expression)
        {
           succeeded = true;
           // ....
        }
    }
    
    if(!succeeded)
    {
       // ....
    }