Assume I have the following function:
// Precondition: foo is '0' or 'MAGIC_NUMBER_4711'
// Returns: -1 if foo is '0'
// 1 if foo is 'MAGIC_NUMBER_4711'
int transmogrify(int foo) {
if (foo == 0) {
return -1;
} else if (foo == MAGIC_NUMBER_4711) {
return 1;
}
}
The compiler complains “missing return statement”, but I know that foo never has different values than 0 or MAGIC_NUMBER_4711, or else my function shall have no defined semantics.
What are preferable solutions to this?
Is this really an issue, i.e. what does the standard say?
Sometimes, your compiler is not able to deduce that your function actually has no missing return. In such cases, several solutions exist:
Assume the following simplified code (though modern compilers will see that there is no path leak, just exemplary):
Restructure your code
This works good if you can interpret the if-statement as a kind of firewall or precondition.
abort()
Return something else accordingly. The comment tells fellow programmers and yourself why this is there.
throw
Disadvantages of Single Function Exit Point
flow of control control
Some fall back to one-return-per-function a.k.a. single-function-exit-point as a workaround. This might be seen as obsolete in C++ because you almost never know where the function will really exit:
Looks nice and looks like SFEP, but reverse engineering the 3rd party proprietary
libfooreveals:This argument does not hold true if
bar()isnothrowand so can only callnothrowfunctions.complexity
Every mutable variable increases the complexity of your code and puts a higher burden on the cerebral capacity on your code’s maintainer. It means more code and more state to test and verify, in turn means that you suck off more state from the maintainers brain, in turn means less maintainer’s brain capacity left for the important stuff.
missing default constructor
Some classes have no default construction and you would have to write really bogus code, if possible at all:
That’s quite a hack just to get it declared.