3 ms·
I prefer to avoid multiple return statements and follow the single-return-at-the-end rule. However, I happily make exceptions for: a) Simple shortcut checks a
by marshray 14y ago
I prefer to avoid multiple return statements and follow the single-return-at-the-end rule.
However, I happily make exceptions for:
a) Simple shortcut checks at the top of the function. These tend not to increase the complexity of the control flow and can really simplify it.
void free(void * p)
{
if (!p) return;
... rest of function
}
b) Cases where it's just plain unnatural to do it any other way. This can occur with state machines and complex loops.
When I do this, I make sure to put a comment way out on the right.
void process_bytes(unsigned char * p)
{
...
for (;;)
{
...
switch (loop_state)
{
...
case specific_case:
switch (input_symbol)
{
...
case end_symbol:
return; //----- note inner return
...
}
break;
...
}
}
}
Before folks jump on me for having nested switch statements or "complex loops" in the first place, let me point out that when I write this type of code it's usually because I'm processing a data format defined by somebody else.