I did some research to find out why a missing return cannot be an error but is undefined behavior instead. I found this comment in a bug report that uses the following example to illustrate why it cannot be an error:
template<typename T> T maybe_call(std::function<T(void)> f) { if (f) return f(); else abort_program(); // Cannot write a return here, because we have no way to create a value of t }
Note that this example is completely valid code. It has no return on all branches, but still there is no UB. That explains why not having a return on all branches is UB, not an error. The example could be "fixed" to declare abort_program();
as [[noreturn]]
to make it less of a counter argument. I doubt that compilers would have problems to correctly diagnose this example. If missing a return would be turned into an error, rules would maybe have to change a bit, because only with the [[noreturn]]
the above example can be diagnosed correctly.
However, what I am looking for is a different example where the compiler cannot detect a missing return. That comment also mentions that cases exists that cannot be diagnosed by the compiler, but I fail to find such an example.
If the warning would be reliable (false positives like the one above aside) I could treat the warning as error to be on the safe side.
Are there really cases where a compiler cannot detect a missing return? Is it only in pathological code, or can it happen in every day code too? Can I rely on the warning?
To make it answerable, lets concentrate on gcc(latest version): In what case gcc fails to warn for a missing return?