Thread overview
[Issue 16194] auto return type inference depends on return statement order
Jun 22, 2016
hbaelx@hotmail.com
Jun 22, 2016
ZombineDev
Dec 17, 2022
Iain Buclaw
Oct 09, 2023
RazvanN
June 22, 2016
https://issues.dlang.org/show_bug.cgi?id=16194

hbaelx@hotmail.com changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
                 CC|                            |hbaelx@hotmail.com

--- Comment #1 from hbaelx@hotmail.com ---
In other words, the compiler apparently extracts info about the return type from the first return statement it comes across, rather than trying to find a common type that matches all of the return statements.

As an obvious workaround, I suggest you avoid using the auto keyword here. The compiler might have some trouble looking for common types, and I doubt this is something that need urgent attention.

--
June 22, 2016
https://issues.dlang.org/show_bug.cgi?id=16194

--- Comment #2 from ZombineDev <petar.p.kirov@gmail.com> ---
No, I think this is specific only to class sub-typing. For example the following compiles successfully and prints "4", "3.4" and "99". In other words, it actually finds the common type of all return statements (in this case - double)

void main()
{
    import std.stdio;
    fun(2).writeln();
    fun(4).writeln();
    fun(6).writeln();
}

auto fun(int a)
{
    if (a < 3)
        return 4;
    else if (a < 5)
        return 3.4;
    else
        return 'c';
}

I'm not particularly bothered by this deficiency of the compiler, just wanted to report it.

Also note that this deficiency is does not affect type inference of array literals:

void main()
{
    import std.stdio;
    [1, 'c', 3.4].writeln();
    [2.3, 'c', true].writeln();
    ['c', 2, 3.5].writeln();
    [new A(), new B(), new C()].writeln();
    [new B(), new A(), new C()].writeln();
    [new C(), new B(), new A()].writeln();
}

class A {}
class B : A {}
class C : A {}

Prints:
1, 99, 3.4]
[2.3, 99, 1]
[99, 2, 3.5]
[test.A, test.B, test.C]
[test.B, test.A, test.C]
[test.C, test.B, test.A]

--
December 17, 2022
https://issues.dlang.org/show_bug.cgi?id=16194

Iain Buclaw <ibuclaw@gdcproject.org> changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
           Priority|P1                          |P3

--
October 09, 2023
https://issues.dlang.org/show_bug.cgi?id=16194

RazvanN <razvan.nitu1305@gmail.com> changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
                 CC|                            |snarwin+bugzilla@gmail.com

--- Comment #3 from RazvanN <razvan.nitu1305@gmail.com> ---
*** Issue 24178 has been marked as a duplicate of this issue. ***

--