I think it's also OK with extra returns at the start of a function, for
quick exit. So you might have something like this:
int sortOfSquareRoot(int x) {
if (x < 0) return 0;
... big lump of code ...
return y;
}
Have an early return saves a layer of bracketing and indentation, and
should be quite clear in such cases.
But multiple returns in the middle of a function are often hard to
trace, and that's never a good idea.
I've got to admit that I'm a big fan of multiple returns when
it comes to error handling. A lot of stuff I write starts with
checking the function arguments, and if one if them isn't kosher
I return immediately with an error value. And even later, when
something doesn't add up and there's nothing within the function
that can be done I have no qualms returning at that point with
a return value to indicate that something went wrong.
Typical example is a function that's supposed to send some command
to a device. If the input to the function is goofy I bail out
immediately. If I find that the state of the device isn't com-
patible with what the function is supposed to do with the device
I bail out, immediately. If there's a problem that can't be fixed
with communicating with the device I bail out, immediately. If I
would follow the mantra of "only one return" such a function would
be a complete mess - too many layers of "if" and "else".
Other languages have exceptions. I'd love to have them in C, to
be honest. And throwing an exception is, basically, a return on
steroids. Why have I never seen a similar criticism of exceptions
but lots of complaints about multiple returns as if they would be
something the devil invented to make live even more miserable?
My impression is that this "no multiple returns" was originally
about practices where functions did lots of different things that
shouldn't have been done in a single function and that this has
morphed into a mantra that isn't allowed to be questioned any-
more. Things like what the OP (in princip;e) proposed like
int fail = OK;
while ( 1 ) {
if ( fail = do_something_1( ) )
break;
if ( fail = do_something_2( ) )
break;
...
}
return fail
etc. isn't any different from multiple returns, just harder to
read. It follow the dogma of "no multiple returns" by the letters
but not by the spirit.
My take on it is to return immediately whenever there's something
going wrong, but not to mis-use multiple returns to write functions
that do several, unrelated things. Multiple returns aren't a pro-
blem per se but only when used for the wrong reasons (just like
goto's).
Regards, Jens