One return from a function: a good idea?
All C/C++ functions have a single point of entry and it is widely thought that a single point of exit is logical. Indeed, a number of programming standards [MISRA C for example] insist on this approach. The logic is that a single return statement makes for clearer, easier to read code. Additionally, a single exit point means that there is less chance of failing to execute function exit code, which may deallocate resources etc. Such an error leads to memory leaks and the like. The contrary argument is that an early return might avoid the need for some convoluted logic to direct the execution flow to the end of the function – a nest of if … else constructs can be hard to read.
I have been pondering an alternative approach that might deliver the best of both worlds …
When I come across complex if … else constructs, my mind always turns to the use of a switch statement, as this almost always results in clearer code. Compilers are also likely to generate efficient code from a switch, which is a bonus. I figured that I might use a switch to code a function as a state machine. Here is my quick and dirty outline code for this:
#define PARAMCHECK 1 #define ALLOCATERESOURCES 2 #define PARAMERR 3 #define RESOURCEERR 4 #define PROCESS 5 #define PROCESSERR 6 #define COMPLETE 7 int fun(int p) { int Exit=0; int State=PARAMCHECK; while (!Exit) { switch (State) { case PARAMCHECK: // check parameters ... if (OK) State = ALLOCATERESOURCES; else State = PARAMERR; break; case ALLOCATERESOURCES: // allocate resources ... if (OK) State = PROCESS; else State = RESOURCEERR; break; case PROCESS: // // *** do main processing here *** // // occasional error checking: if (ERROR) { State = PROCESSERR; break; } // State = COMPLETE; break; case PARAMERR: case RESOURCEERR: Exit = TRUE; break; case PROCESSERR: case COMPLETE: // deallocate resources ... Exit = TRUE; break; } } return State; }
Does it make sense? Feel free to pull my code apart via email or social media.
Comments
Leave a Reply
You must be logged in to post a comment.
I am guessing you are familiar with Miro Samek and his state charts book. http://www.state-machine.com/
Good stuff, and I recommend it in comments and forums all the time.
Also, Go the language lets you return multiple values from a function. https://duckduckgo.com/?q=golang+return+multiple+values+from+a+function&t=canonical&ia=qa
Fun stuff.
Interesting approach but if a single if-statement takes 7 cases in the switch, how many will it take for 3 levels of nested if-statements (which are arguably still readable, unlike 21 cases…). Next question would be the impact on run-time and code density: it would be nice to have some figures…
I am not sure that such a multiplication would result from such nesting.
Also, compilers generally do a very good job of creating optimal code with switch statements.