Why does this C++ snippet compile (non-void function does not return a value) [duplicate]

This is undefined behavior from the C++11 draft standard section 6.6.3 The return statement paragraph 2 which says:

[…] 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. […]

This means that the compiler is not obligated provide an error nor a warning usually because it can be difficult to diagnose in all cases. We can see this from the definition of undefined behavior in the draft standard in section 1.3.24 which says:

[…]Permissible undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment (with or without the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message).[…]

Although in this case we can get both gcc and clang to generate a wanring using the -Wall flag, which gives me a warning similar to this:

warning: control reaches end of non-void function [-Wreturn-type]

We can turn this particular warning into an error using the -Werror=return-type flag. I also like to use -Wextra -Wconversion -pedantic for my own personal projects.

As ComicSansMS mentions in Visual Studio this code would generate C4716 which is an error by default, the message I see is:

error C4716: ‘Min’ : must return a value

and in the case where not all code paths would return a value then it would generate C4715, which is a warning.

Leave a Comment