Pergunta

I've two pieces of code:

A do while loop:

do
{
    errorflag=0;
    ...
    if(cond1)
    {
        errorFlag=12;
        break;   // Error Conditions
    }
    .
    .            // Processing
    .
    if(cond2)  
    {
        errorflag=56;
        break;
    }
     .
     .

} while (0);

A goto label:

errorflag=0;
if(cond1)
{
     errorflag=12;
     goto xy;
 .
 .
 .
 .
if(Cond2)
{
     errorflag=56;
     goto xy;
}
.
.
.

xy:

Which one is better? Please give me the details why? or is there any better way to do this? We are optimizing the code. We are most looking into these kind of big loops. Is assembly level, there is not that much scope for optimisation. Please provide your inputs.

I dont like to use else-if since, it is again a overhead of checking one more condition. So directly exit when there is an issue.

I feel after this edit my question makes sense

Thanks in advance

Foi útil?

Solução

The choice here, base on your question, is do-while and goto.

I recommend you choose do-while.

I discourage you to use goto. That will lead you to spaghetti-code later on.

You can have alternatives like if and if-else to come up with the same result.

Say no to goto

Outras dicas

Option 3:

void frobnicate(arguments) 
{
  if (cond1) return;
  if (cond2) return; 

  ...
}

frobnicate(the_arguments)

Pick a meaningful name, and keep it short.

They generate the same code (assuming the compiler's worth consideration) so the difference is one of which is most easy to understand and whether the do/while interferes with other loop constructs that are about. If there is such interference, use gotos. Otherwise don't; they're less clear (usually).

And look carefully to see if your function is over-complex and should be refactored into multiple functions with a clearer purpose and simpler control flow.

Seriously? Have you never heard of else?

if (cond1)
{
    //stuff
}
else if (cond2)
{
    // more stuff
}
// etc

else
{
    // default
}

Edit

I misread the question. I'm going to leave the old answer here though because the comments don't make sense otherwirse.

The proper way to code exactly as per what is in the question is:

if (!cond1)
{
    .
    .
    .
    .
}

In both cases in the question, the if (cond2) part has no effect (assuming cond2 has no side effects) because they both cause a jump to the statement that would be executed next anyway. That's why I left it out.

goto is evil. You should only use gotos when there is absolutely no other way to do this. gotos can lead to unpredictable spaghetti code (hard to read, to understand, to debug, very prone to mistakes on maintenance phases).

I believe that an infinite while loop with conditional break statements is still better, although it's more readable when the conditions are expressed in the while statement.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top