Immutable + goto?

Frits van Bommel fvbommel at REMwOVExCAPSs.nl
Thu Mar 19 08:58:27 PDT 2009


dsimcha wrote:
> import std.stdio;
> 
> uint bar = 0;
> 
> void main() {
>     start:
>     immutable uint foo = bar;
>     bar++;
>     writeln(foo);
>     goto start;
> }
> 
> foo changes in this case.  Is this a real bug, or is it considered undefined
> behavior to use goto in this way?

I disagree: foo doesn't change there :þ.

Declaring a local variable like that actually creates a new scope behind 
the scenes, containing everything up to '}' (taking nesting into 
account, of course). This means the label is outside the scope of foo, 
and foo gets "destroyed" when the goto jumps out of it. A "new" foo is 
created (with a different value) when the program enters its scope.

This is basically the same as:
-----
while (true) {
     immutable uint foo = bar;
     bar++;
     writefln(foo);
}
-----
or even:
-----
while (true) {
     void nested_fn(uint foo) {
         bar++;
         writefln(foo);
     }
     nested_fn(bar);
}
-----
which show the behavior more clearly.



More information about the Digitalmars-d mailing list