f() does not return even though it's signature say it should. Why is the reason for allowing this to compiling? Is there a reason the C standard does not require the compiler to make it fail?
I know that it is Undefined behavior and all, but why is it allowed in the first place? Is there a historical reason?
double f(){}
int main()
{
f();
return 0;
}
If no return statement appears in a function definition, control automatically returns to the calling function after the last statement of the called function is executed. In this case, the return value of the called function is undefined.
tl;dr: C++ functions do not require a return keyword in them to be well-formed and compile, though it will likely cause undefined behaviour. Your specific compiler may also warn or error.
The analyzer has detected a non-void function with an execution path that does not return a value. Such a function results in undefined behavior. Flowing off the end of a non-void function with no 'return' results in undefined behavior.
Is there a reason the C standard does not require the compiler to make it fail?
By invoking undefined behavior, the C standard allowed the compilers to be less complicated. There is indeed some cases, such as if
statements, in which it is hard to say whether the function returns a value or not:
int f(int n)
{
if (n > 0) return 1;
}
f(5)
, it is easy for the compiler to say that the
function is correct. f(-5)
, it is also easy to detect
an undefined return value.But if the argument comes from user input for example, how should the compiler be able to know whether the function returns a value? Since this could both a valid or a wrong program, C standard allows the compilers to do what they want. C is designed to be as smart and simple as possible.
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