Biswapriyo
Biswapriyo

Reputation: 4251

How to optimize code for multiple return value?

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?

Upvotes: 3

Views: 123

Answers (4)

Serge Ballesta
Serge Ballesta

Reputation: 148880

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.

Upvotes: 2

Bathsheba
Bathsheba

Reputation: 234645

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.

Upvotes: 2

Hatted Rooster
Hatted Rooster

Reputation: 36463

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);

Upvotes: 6

mehta-rohan
mehta-rohan

Reputation: 1341

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.

Upvotes: 0

Related Questions