Unlike Java, in C/C++ following is allowed:
int* foo ()
{
if(x)
return p;
// what if control reaches here
}
This often causes crashes and hard to debug problems. Why standard doesn't enforce to have final return for non-void
functions ? (Compilers generate error for wrong return
value)
Is there any flag in gcc/msvc to enforce this ? (something like -Wunused-result
)
The “missing return statement” message occurs when a method does not have a return statement. Each method that returns a value (a non-void type) must have a statement that literally returns that value so it can be called outside the method.
How to resolve the error? In order to solve the missing return statement error, we simply need to add the return statement to the method just like to the one we did in case one. So, we will return the some value of the same type which we used before the name like as: public static String checkNumber( int number) {
A compile error happens when the compiler reports something wrong with your program, and does not produce a machine-language translation. You will get compile errors.
It is not allowed (undefined behaviour). However, the standard does not require a diagnostic in this case.
The standard doesn't require the last statement to be return
because of code like this:
while (true) {
if (condition) return 0;
}
This always returns 0, but a dumb compiler cannot see it. Note that the standard does not mandate smart compilers. A return
statement after the while
block would be a waste which a dumb compiler would not be able to optimise out. The standard does not want to require the programmer to write waste code just to satisfy a dumb compiler.
g++ -Wall is smart enough to emit a diagnostic on my machine.
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