But the compiler says no error and it works when executed.
This depends on your warning level.
For example, MSVC when compiled with anything from /W1
to /W4
, says:
warning C4715: 'test_return' : not all control paths return a value
You can even turn the warning into an error with the /WX
option:
error C2220: warning treated as error - no 'object' file generated
warning C4715: 'test_return' : not all control paths return a value
GCC or other compilers have similar options. Just read the documentation or research the options in Google.
The philosophy in C++ is that it is the developer's fault if they do not carefully consider their compiler settings, use low warning levels or ignore warnings. If you do any of those things, then the result will often be undefined behaviour at run-time, like in your case (a missing return value).
You should also know the C++ standard does not distinguish between errors and warnings; it knows only so-called "diagnostic messages". Whether the compiler should turn these into warnings or errors is not mandated anywhere. However, no such diagnostic message is required for a missing return value. The warning (or error) you receive for your code is therefore optional from the C++ standard point of view. That's OK, because compilers are free to provide more output, even in situations where no diagnostic message is required.
By the way...
it works when executed.
That's just a coincidence. Undefined behaviour means that everything can happen, including the desired behaviour every now and then.