-3

What is the difference between these two functions in terms of code execution. The result is the same, but will the compiler optimize both to the same outputted assembly?

void some_func() 
{
   if (!something)
      return;
   //rest of code
}

void other_func() 
{
   if (something) {
      //rest of code
   }
}
Bob Bobby
  • 134
  • 1
  • 10
  • 1
    Why don't you just check the compiler output? – UnholySheep Jun 22 '17 at 19:53
  • 3
    There's no difference. Whether the compiler will optimize them the same depends on the compiler. – Barmar Jun 22 '17 at 19:53
  • 2
    But even if it doesn't, the difference will be negligible. – Barmar Jun 22 '17 at 19:53
  • 4
    [Premature optimization is the root of all evil](http://c2.com/cgi/wiki?PrematureOptimization) – Barmar Jun 22 '17 at 19:53
  • I use case(1) when checking pre-conditions (or throw an exception). It makes it obvious where the testing (of the pre-conditions) ends and the actual code starts. – Richard Critten Jun 22 '17 at 19:54
  • I prefer the former because it instantly tells me there's a range of input to which this function doesn't apply at all. With the other I'll expect perhaps there's something else to do for the rest at a later part of the function. As someone that regularly has to get up to speed on what functions do and why so I can fix them...it's a noticeable difference. Can be the difference between me having to understand that function right now and not because whatever I'm dealing with might not fall in the function's range. – Edward Strange Jun 22 '17 at 19:58

2 Answers2

3

It depends on the compiler for exact translation of assembly instructions, but it is most likely exactly the same and/or so negligible it is irrelevant.

This is often used for readability over any sort of speed optimization attempt.

Easton Bornemeier
  • 1,918
  • 8
  • 22
0

The former is preferred. It is simpler and more readable.

void foo()
{
    if( error_condition)
    {
       // Handle error
       return;
    }

    // Carry on

    if( other_error_condition)
    {
       // Handle error
       return;
    }

    // Carry on

    // Done
}

Some argue that there should only be one return from any function, but this has not been a best practice for quite a long time and is a left over myth from assembly days.

The alternative results in a lot of nesting ugliness

void foo()
{
    if( !error_condition)
    {
       // Do stuff

       if ( !other_error_condition )
       {
           // Do other stuff
       }
       else           
       {
            // Handle error
       }
    }
    else
    {
        // Handle error
    } 

    // Done
}
Christopher Pisz
  • 3,757
  • 4
  • 29
  • 65