If a function returns no value, with a valid return type, is it okay to for the compiler to return garbage?

In C++, such code has undefined behaviour:

[stmt.return]/2 … Flowing off the end of a function is equivalent to a return with no value; this results in undefined behavior in a value-returning function. …

Most compilers will produce a warning for code similar to that in the question.

The C++ standard does not require this to be a compile time error because in the general case it would be very difficult to correctly determine whether the code actually runs off the end of the function, or if the function exits through an exception (or a longjmp or similar mechanism).

Consider

int func3() {
    func4();
}

If func4() throws, then this code is totally fine. The compiler might not be able to see the definition of func4() (because of separate compilation), and so cannot know whether it will throw or not.

Furthermore, even if the compiler can prove that func4() does not throw, it would still have to prove that func3() actually gets called before it could legitimately reject the program. Such analysis requires inspection of the entire program, which is incompatible with separate compilation, and which is not even possible in the general case.

Leave a Comment