Return type inference

Dmitry Olshansky dmitry.olsh at gmail.com
Thu May 17 06:40:56 PDT 2012


On 17.05.2012 17:10, Tobias Pankrath wrote:
> This does not work and I can see why.
>
> ---
> auto foo(int x)
> {
> if(x < 0)
> return foo(-x);

Pluck in other condition then x < 0 and you may see it's not so easy. 
Basically compiler has to deduce that recursion stops and trace down to 
the bottom of it.

> return x;
> }
> ----
>
> DMD 2.059 says:
> oopsc/compiler/test.d(7): Error: forward reference to foo
> oopsc/compiler/test.d(14): Error: forward reference to foo
>
> For the human reader it is easy to see that the return type of
> foo should be int. Could the following rule be added to make dmd
> see this, too?
>
>> If there are multiple ReturnStatements, the types of them must match
>> exactly. If there are no ReturnStatements, the return type is inferred
>> to be void.
>> <new>
>> If the function is called recursively the type of the result of this
>> call is inferred in the same way. If the recursive call is part of a
>> return statement > then this statement is not considered for type
>> inference. If all return statements are discarded in this way, it is
>> an error.
>
>


-- 
Dmitry Olshansky


More information about the Digitalmars-d mailing list