Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which one is better? do{} while(0); or goto xy; [closed]

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

like image 252
Rajeev Avatar asked Jan 21 '23 22:01

Rajeev


2 Answers

Option 3:

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

  ...
}

frobnicate(the_arguments)

Pick a meaningful name, and keep it short.

like image 119
Victor Nicollet Avatar answered Jan 31 '23 05:01

Victor Nicollet


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.

like image 32
Donal Fellows Avatar answered Jan 31 '23 07:01

Donal Fellows