Jorge Rivera wrote:
Sam Holden wrote:
On Sun, 18 Jan 2004 23:57:24 GMT,
exits funnel <ex*********@NOSPAMyahoo.com> wrote:
It's true that if I turn the warning level up, the compiler does warn
me about missing return statements but the question still remains
(assuming
my compiler is compliant with the spec): Why is a return type
mismatch
an error while no return statement at all isn't? What's the
rationale?
Becsaue a return type mismatch causes a type error, but a missing
return might be intended. There's already a reply giving an example
of a case in which leaving off the return might be valid.
I have not seen this reply.
Would you mind restating what is so valid about ignoring the return
type of a function or method that you design?????
If your function will never reach a certain place, it's just unecessary
if you need to write a return statement for that unreachable part. For
example:
string foo(const string& s)
{
if (s == "blah")
return do_something();
else if (s == "whatever")
return do_something_else();
else
return some_error;
// this part can never be reached. Why should one be forced to
// add a return statement here?
}
If you add that return, some compilers will even warn you about the fact
that you wrote unreachable code.
Note: Java requires the return, and the idiot compiler not noticing
that the end of a function was unreachable was enough to drive me mad
(I dislike being forced to add the extra code which will never be
executed and the comment required to warn future readers of why the
code was added...
I agree that the compiler should catch those return errors, however, I
fail to understand why ignoring the return type of a function is such
a a great idea.
Ignoring it generally isn't, but in specific situations, it is better
than needing to write unreachable code. In my above example, the
compiler could easily find out that the code is unreachable, but it's
not always so obvious, so a programmer might indeed intend to omit a
return because he knows that it can't ever be reached, or at least
shouldn't ever be reached. In the latter case, it makes more sense to
add an assert instead of a return. The compiler might not be able to
know that this place in the function won't never be reached.