Which piece of code is not only reasier to read, but more efficient?
Example 1:
const int size = 10;
bool FindValue( int value )
{
int arr[size][ size];
Load(arr);
bool fFound = false;
if( value != 0 ) // Must have value greater than 0
value--;
if( value < size && arr[value][0] != 0 ) // Ignore 0
for( int i = 0; i < size && !fFound; i++)
for( int j = 0; j < size && !fFound; j++)
if( arr[i][j] == value )
fFound = true;
}
return fFound;
Example 2:
int arr[size][size];
if( value == 0 ) // Must have value greater than 0
return false;
if( value >= size || arr[value][0] == 0 ) // Ignore 0
for( int i = 0; i < size; i++)
for( int j = 0; j < size; j++)
return true;
The second example uses the “dreaded” multiple returns.
Multiple returns do make it harder to know where your function will exit. But having one exit point doesn’t mean it’s any easier to see which value your function will return. And contorting your code just so you can have one exit point isn’t good practice as it can create unneeded indenting (which hurts readability) and can lead you to doing things like putting extra checks in loops (which can lead to performance hits and bugs).
But what if you need to clean something up and having one return at the end makes this easier? Yes, one return does make that easier. But in an age of Object Oriented Programming and exceptions, there’s no guarantee you’ll actually get to that return before you leave the function. If you have cleanup work to do, you should encapsulate it in an object that lives on the stack which calls clean up code in its destructor. Then any clean up is done no matter how you exit the function.
The moral is don’t take every ivory tower thing you learn in class to be black and white. Some practices are just different ways of doing things and others (like the above) will actually hurt you when writing real industry code.