Inline
Inline

Reputation: 2853

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

Upvotes: 1

Views: 193

Answers (3)

R Sahu
R Sahu

Reputation: 206617

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

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

if(!succeeded)
{
   // ....
}

Upvotes: 2

xanth
xanth

Reputation: 172

I don't know anything about your code but you could do this:

void on_error ()
{
  //error stuff
}

int main ()
{
    if(first_expression)
    {
        if(second_expression)
        {
            // ....
        }
        else
            on_error();
    }
    else
        on_error();
}

or even better:

void job()
{
    if(first_expression)
    {
        if(second_expression)
        {
            // ....
        }
        else
            throw;
    }
    else
        throw;
}

int main () {
  try
  {
    job();
  }
  catch ()
  {
    // err stuff 
  }
  return 0;
}

Upvotes: 3

ixSci
ixSci

Reputation: 13698

You can rewrite it as follows:

if(first_expression)
{
    // ....
    if(second_expression)
    {
        // ....
    }
}
if(!first_expression || (first_expression && !second_expression))
{
}

Upvotes: 0

Related Questions