CBFalconer said:
James Beck wrote:
... snip ...
Nor do the multiple returns necessarily improve efficiency and/or
code size. In fact I believe (on the basis of some cursory looks)
that GCC for the x86 -O3 or -O2 reorganizes the control flow to
place the actual return at the end in all cases.
So my attitude, based on ease of reading alone, is one exit, with
the sole exception of entry validation tests. Something like:
if (foo) return 1;
else if (bar) return 2;
else {
/* the meat */
}
return foobar;
A well thought out exception to the rule. If it fails early, return
early, and it is obvious why you
have returned the value you did.
In device drivers I have seen and written, the common practice was to put
all of these things up front, e.g.
if(some_condition) return ENODEV;
if(some_other_condition /*based on the input parameters*/) return EFAULT;
etc.
Then, finally, the "meat" when all error checks on the input had been
performed.
I find this more readable than:
retval = 0;
if(some_condition) retval = ENODEV;
if(some_other_condition) retval = EFAULT;
....
if (retval == 0) {
/*meat*/
retval = whatever;
}
return retval;
but your preferences may vary.