https://issues.dlang.org/show_bug.cgi?id=19743
Dennis <[email protected]> changed: What |Removed |Added ---------------------------------------------------------------------------- Keywords| |diagnostic, safe CC| |[email protected] Summary|Foreach loops desugar into |[dip1000] unclear error |code that breaks `return |message when escaping |scope` |variable through foreach | |`ref` Severity|normal |enhancement --- Comment #1 from Dennis <[email protected]> --- Haystack in your example is an `int[9]`, a value type without pointers, so (return) scope doesn't apply to it. When you `return &val;`, you're escaping a pointer to the expired stack frame containing your `haystack` parameter, so an error is in place. To make `find` valid, your haystack should be passed by `ref`, and then it compiles: ``` int* find(return ref int[9] haystack, int needle) @safe { foreach (ref val; haystack) if (val == needle) return &val; return null; } void main() @safe { int[9] haystack = [0, 10, 5, 6, 2, 3, 9, 4, 5]; int* foundVal = haystack.find(3); } ``` However, "scope variable __r2 may not be returned" is not a good diagnostic, so I'm changing this issue to be about that. --
