Is it legal C++ to define a function with a non-void return type that allows control to reach the end of the function instead of reaching a return statement?
gcc
and clang
only issue warnings for this. Is code that does this legal or are these compilers just being generous?
gcc:
warning: no return statement in function returning non-void [-Wreturn-type]
clang:
warning: control reaches end of non-void function [-Wreturn-type]
If this is legal, is there a defined behavior for what value will be returned?
As already stated by Bathsheba, flowing off the end of a non-void function is indeed undefined behavior. The reason why this is a warning, not an error, is that you might be able to proof that this will never happen. For example consider this:
// My magic function.
// It is forbidden to call it with values between -5 and 5
bool fun (int i) {
if (i >= 5)
return true;
if (i <= -5)
return false;
}
Now you have well defined behavior as long as the users of the function read the comment carefully. This is obviously a dangerous thing to do, so the compiler warns you not to do it.
Edit: As MSalters mentioned, this is less dangerous for private member functions because the class invariant can guarantee that the function is never used incorrectly. Consider this example:
// Every member function of SomeClass makes sure
// that i_ is in the legal range when it's done
class SomeClass {
public:
SomeClass () : i_{27} {}
// Possibly more public or private functions that all make sure i_ stays valid
private:
bool foo () {if (i_ > 3) return true;}
int i_;
};
Now you (as the class maintainer) can make sure that i_
is always at least 4
and foo
will always work fine. Personally, I would still avoid that because it hurts maintainability and readability, but it is better than the free version because now "only" all class maintainers need to worry about this invariant/can make a mistake.
From C++ Standard, 6.6.3:
Flowing off the end of a function is equivalent to a return with no value; this results in undefined behaviour in a value-returning function.
So not having an explicit return value is undefined behaviour.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With