Goran said:
Its bad practice to only have one return point from a function as the
single return far too often results in a plurality of status flags and
nested if-statements, all needed to go from the wanted return point to
the mandated return point.
If you need multiple returns or many status flags or multiply-nested
"ifs" to make your function readable, then it's probably too big or just
badly designed. The alternative is that it's necessarily complex in
which case having a status flag would improve readbility. e.g.
for (i = 0; i < MAX; i++) { /* False assumption from the next guy
* to work on this code: Ah, we only
* leave this loop when i reaches "MAX"
*/
....
if (foo(i) > 27) {
return 1; /* Question from the next guy to work on
* this code: Huh? Why are we returning here?
*/
}
}
/* do success leg stuff */
return 0;
vs
rslt = SUCCESS;
ret = 1;
for (i = 0; (i < MAX) && (rslt == SUCCESS); i++) {
....
if (foo(i) > 27) {
rslt = OUTOFRESOURCES;
}
}
if (rslt == SUCCESS) {
/* do success leg stuff */
ret = 0;
}
return ret;
Not only is the second version easier for the next guy to understand,
it's easier to debug if you want to, say, stick in a printf() to dump
the return code just before the function returns since now you do it in
one place instead of many and you have a variable "ret" to dump.
Disclaimer - the above is for necessarily complex functions, not for
every function, and we're discussing whether or not to use multiple
returns, not whether the above structure using a status flag is better
or worse than the equivalent with "goto"s.
Regards,
Ed.