Bug 2023 – Returning from foreach body doesn't work as expected.
Status
RESOLVED
Resolution
INVALID
Severity
normal
Priority
P2
Component
dmd
Product
D
Version
D2
Platform
x86
OS
Windows
Creation time
2008-04-21T04:59:00Z
Last change time
2015-06-09T01:14:38Z
Assigned to
bugzilla
Creator
samukha
Comments
Comment #0 by samukha — 2008-04-21T04:59:28Z
The bug is reproduced by the following code. Instead of making foo return, the 'return' statement in foo's foreach body breaks the loop:
----
struct S
{
int a[];
int opApply(int delegate(ref int) dg)
{
foreach (x; a)
{
if(dg(x))
return 1;
}
return 0;
}
}
void foo()
{
auto s = S([1, 2, 3]);
foreach (x; s)
{
if (x == 1)
return; // breaks the loop instead of returning from foo.
}
assert(false); // should never reach here.
}
void main()
{
foo();
}
----
Comment #1 by wbaxter — 2008-04-21T07:57:12Z
Here's my opportunity to restate my opinion that the programmer should not be responsible for passing around opaque magic values generated by the compiler. At least not in a supposedly modern language.
I wrote a proposal about how to make opApply more user-friendly
Here: digitalmars.D:64686
And a few clarifications here: digitalmars.D:64706
Unfortunately I think it really requires macro() to make it pretty.