Suppose a class exists as follows:
class Foo
{
void do_after_something()
{
//some code here
return;
}
void do_something()
{
//some code here
return do_after_something(); //returning another (void) function
}
};
JAVA is clearly opposed to something like the above, Borland C++ compiler issues a warning, MS VC++ does not complain.
My question is: Should returning from a void function be logically (theoretically) correct?return do_after_something();
as opposed to:
do_after_something();
return;
or is it all implementation (compiler/language) dependent?
Philosophically, you could argue that returning the result of a void
-returning function should be allowed but, sadly, that's not the case here, at least for Java.
It is valid for C++ however. If you try out the following program:
#include <iostream>
void xyzzy(void) {}
void plugh(void) { return xyzzy();}
int main() {
std::cout << "Hello\n";
plugh();
return 0;
}
it will work fine.
This is detailed in ISO C++11 6.6.3 /3
:
A return statement with an expression of type
void
can be used only in functions with a return type ofcv void
; the expression is evaluated just before the function returns to its caller.
So it's really equally valid to argue that the Java way is correct if you think of void
as not an actual type, but as an absence of something. For example, when you have:
int xyzzy(void) { return 42; }
in C, you're not forced to provide an argument of the correct (non-)type, such as with:
void plugh;
int twisty = xyzzy(plugh);
Ditto, the C++ way is correct as well, but in a different way - the languages are what they are.