Home > Software engineering >  Is it more efficient to remove the else statement in C?
Is it more efficient to remove the else statement in C?

Time:07-07

Is there any difference to a compiler between this code:

if(something == true) {return -1}
else {return 0}

and this code:

if(something == true) {return -1}
return 0;

Does the compiler interpret these differently and if so would the second example be more efficient in C?

CodePudding user response:

These two program snippets do the same. C compilers are free to generate different (slower or faster) code as long as it does the same. Most C compilers will generate the same code though, because they build the same intermediate representation (see the answer by Yves Daoust) first, and then they generate the code from that.

CodePudding user response:

It won't, but the convention is to not write an else statement after an if statement that returns something.

CodePudding user response:

Generally any modern compiler should generate the same machine code for trivial examples such as this. Just watch the disassembly from any compiler such as gcc, enable optimizations and see for yourself. Examples:

#include <stdbool.h>

int example1 (bool something)
{
  if(something == true) 
    return -1;
  else 
    return 0;
}

int example2 (bool something)
{
  if(something == true) 
    return -1;
  return 0;
}

int example3 (bool something)
{
  return something==true ? -1 : 0;
}

int example4 (bool something)
{
  for(int i=something; i!=false; i  )
  {
    if(i)
      return -1;
  }
  return 0;
}

https://godbolt.org/z/1Kxxsbj9s

All of these examples boil down to the very same machine code, even the contrived example4 one:

    movzx   eax, dil
    neg     eax
    ret

That is, grab the input parameter and replace it with it's two's complement (neg), meaning either 1 -> -1 or 0 -> 0.

The optimizer also didn't generate any branch (conditional execution paths) which would have made the code slower on all high-end CPUs.

So which form to use is mostly a matter of style. Various safety standards (ISO 61508, ISO 26262, MISRA C etc) tend to quite subjectively frown at multiple return in a single function, so if you care about that, example3 might actually be the best one.

  •  Tags:  
  • c
  • Related