Synopsis: | There shall be exactly one "return" statement in a function returning non-void. |
Language: | C |
Severity Level: | 9 |
Category: | Statement and Blocks |
Description: |
Justification More than one exit point indicates a forced break in control flow and, like any break in control flow, leads to code which is more difficult to read and maintain. Example 1 if (i > 10) { return (i - 10); /* WRONG */ } else { return (i); /* WRONG */ } Example 2 var result = 0; ... if (i > 10) { result = i - 10; } else { result = i; } return result; /* RIGHT */ Exception Multiple returns are allowed in case of simple (failing) tests at the beginning of a function. This is called the fail-fast pattern. Note Do not confuse an exit function call with a "return" statement: a "return" statement is to return to its caller, where an exit statement is to terminate the program execution. |