How to optimize code for multiple return value?

Viewed 114

Here an example of my code:

void MyFunc()
{
    if(funcA(varA) == 0)
    {
        if(funcB(varB) == 0)
        {
            if(funcC(varC) == 0)
            {
                //Success funcC
            }
            else
            {
                //error with funcC
            }
        }
        else
        {
            //error with funcB
        }
    }
    else
    {
        //error with funcA
    }
}

So the code will be like, if funcA() returns zero ONLY then execute funcB(), if funcB() returns zero ONLY then execute funcC() and so on. My question is how can I replace that nested if...else statements with some other optimized method?

4 Answers

To prevent a bunch of scopes and if's nested you can fail-fast instead:

if(funcA(varA)) // if funcA returns 0, only then proceed
  return;

if(funcB(varB))
  return;

if(funcC(varC))
  return;

You can expand the ifs if you want to print some error :

if(funcA(varA))
{
  //error..
  return;
}

Or if you don't need such information, use a short-circuiting one-liner, this will only run funcB if funcA returns 0 etc:

!funcA(varA) && !funcB(varB) && !funcC(varC);

Your code is exactly equivalent to

void MyFunc()
{
    if(funcA(varA)){
        //error with funcA
        return;
    }
    if(funcB(varB)){
        //error with funcB
        return;
    }
    if(funcC(varC)){
        //error with funcC
        return;
    }
    //Success funcC [sic.]
}

which also scales better in the sense that there's an obvious pattern should you need a funcD.

Don't.

Unless your coding standards mandates it, the original code is clear enough and provides places for commenting if needed.

In C language, low level optimization should be left for the compiler. The responsability of the programmer is to produce readable code with the correct high level algorithms.

The number of lines matters in optimization in old basic or in javascript, not in C.

try

void MyFunc()
{
    if(funcA(varA) == 0 && funcB(varB) == 0 && funcC(varC) == 0)
    {

    }
    else
    {

    }
}

if your first function evaluates to desire results only then funcB is called and same in case of next functions. The only disadvantage is you can't check which of them doesn't produce desire result.

Related