The scope of scope(exit)
Hasan Aljudy
hasan.aljudy at gmail.com
Thu Mar 9 20:53:49 PST 2006
Derek Parnell wrote:
> The following code did not work as I expected it to.
>
> -----------------------
> import std.stdio;
> int Foo(int x)
> {
> int y;
> y = x;
> scope(exit) { if (x < 5) y += 9; }
> return y;
> }
>
> void main()
> {
> int i;
> i = 1;
> writefln("Foo IN %s OUT %s", i, Foo(i));
> i = 7;
> writefln("Foo IN %s OUT %s", i, Foo(i));
> }
> ------------------------
>
> I got ...
>
> Foo IN 1 OUT 1
> Foo IN 7 OUT 7
>
> but expected ...
>
> Foo IN 1 OUT 8
> Foo IN 7 OUT 7
>
> It appears that the return statement is not the last thing executed in the
> function. It appears that it caches the value it is about to return,
> executes the scope(exit) code, then returns the cached value. Which makes
> it difficult for a scope(exit) statement to effect the returned value.
>
I think the documentation should explain these situations a bit more.
More information about the Digitalmars-d-learn
mailing list