[Issue 2023] New: Returning from foreach body doesn't work as expected.

Jarrett Billingsley kb3ctd2 at yahoo.com
Mon Apr 21 05:46:55 PDT 2008


<d-bugmail at puremagic.com> wrote in message 
news:bug-2023-3 at http.d.puremagic.com/issues/...
> http://d.puremagic.com/issues/show_bug.cgi?id=2023
>
>           Summary: Returning from foreach body doesn't work as expected.
>           Product: D
>           Version: 2.012
>          Platform: PC
>        OS/Version: Windows
>            Status: NEW
>          Severity: normal
>          Priority: P2
>         Component: DMD
>        AssignedTo: bugzilla at digitalmars.com
>        ReportedBy: samukha at voliacable.com

> struct S
> {
>    int a[];
>
>    int opApply(int delegate(ref int) dg)
>    {
>        foreach (x; a)
>        {
>            if(dg(x))
>                return 1;
>        }
>
>        return 0;
>    }
> }


You're implementing the opApply wrong.

if(auto result = dg(x))
    return result;

The result of the delegate is an int, not a bool, for a reason.  There are 
many possible return values, not just 1 or 0; you're just faking out the 
runtime by doing so. 




More information about the Digitalmars-d-bugs mailing list