c, java and many other languages do not pay attention to return values.
int i = func()
float f = func()
int func() { return 5 }
float func() { return 1.3
Most languages allow for mixed-mode operations with automatic coercion (e.g. float + int), where multiple interpretations are legal. Without coercion, working with multiple numeric types (short, int, long, float, double) would become very cumbersome; with coercion, return-type based disambigation would lead to hard-to-understand code.
To avoid ambiguity.
a( int )
a( bool )
int b()
bool b()
a( b() ) -- Which b?
Here type inference has a cyclic dependency. Which b
depends on which a
, but which a
depends on which b
, so it gets stuck.
Disallowing overloading of return types ensures that type inference is acyclic. The return type can always be determined by the parameter types, but the parameter types cannot be determined by the return type, since they may in turn be determined by the parameter types you are trying to find.
Perl allows a certain degree of return type variation, in that functions can tell what kind of context they're being evaluated in. For instance, a function that might return an array can see that it's running in a scalar context, and just return the putative length directly, sparing the allocation and initialization of the array just to get its length.
Let's say it was allowed, which one would this call:
func();
That may not the the full answer, but I believe that is one reason why it is not legal.
For a C++ example, consider:
void g(int x);
void g(float x);
g(func());
Which of the overloaded g()
functions would be called?
Allowing these may introduce problems. For example:
int i = func2(func());
int func() { return 5; }
float func() { return 1.3; }
int func2(float a) { return a; }
int func2(int a) { return a; }
This is ambiguous.