The scope of scope(exit)
Derek Parnell
derek at psych.ward
Thu Mar 9 17:58:08 PST 2006
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.
--
Derek
(skype: derek.j.parnell)
Melbourne, Australia
"Down with mediocracy!"
10/03/2006 12:55:29 PM
More information about the Digitalmars-d-learn
mailing list