The following code should print 2 but writes random numbers instead:
void main() @safe
{
import std.stdio : writeln;
writeln(identity(2));
}
int identity(immutable int q) pure nothrow @safe @nogc
{
import std.algorithm : map;
static immutable auto arr = [42];
int getSecondArgument(int a, int b)
{
return b;
}
return arr.map!((int a, int b = q) => getSecondArgument(a, b))[0];
}
Comment #1 by ag0aep6g — 2018-05-26T16:37:31Z
Reduced Phobos away:
----
void main() @safe
{
assert(identity(2) == 2); /* fails; should pass */
}
struct Map(alias fun)
{
int front() @safe { return fun(); }
}
int identity(immutable int q) pure nothrow @safe @nogc
{
int getArg(int b) @safe
{
return b;
}
return Map!((int b = q) => getArg(b))().front();
}
----
Comment #2 by kubo39 — 2019-04-27T07:53:53Z
This should fail to compile, and in this case you can use `lazy int b = q` and will work.
Comment #3 by robert.schadek — 2024-12-13T18:58:54Z