Is this a bug? +goto
Stanislav Blinov
stanislav.blinov at gmail.com
Tue Nov 6 00:13:52 UTC 2018
On Monday, 5 November 2018 at 23:54:59 UTC, MatheusBN wrote:
> Hi,
>
> I posted this in another thread but without any response.
>
> This code:
>
> void main(){
> goto Q;
> int x;
> Q:
> writeln("a");
> }
>
> Gives me this error: "source_file.d(4): Error: goto skips
> declaration of variable source.main.x at source_file.d(5)"
>
>
> Now, if I add a pair of brackets:
>
> void main(){
> {
> goto Q;
> int x;
> }
> Q:
> writeln("a");
> }
>
> It works. So Is this a bug?
No, it's not. Consider replacing that int with a type that has a
destructor:
struct S { ~this() { /* ... */ } }
void main(){
goto Q;
S x;
Q:
writeln("a");
} // <---
Now, what should happen at that closing paren is a destructor
call, x.__dtor. However, goto jumps over initialization of 'x',
which would lead to calling a destructor on an uninitialized
value. That's why the compiler disallows such skips.
But here it's fine:
void main(){
{
goto Q;
S x;
} // <---
Q:
writeln("a");
}
because goto jumps over both initialization *and* destruction,
i.e. neither would even be performed.
I'm guessing you misunderstood the author of that other thread.
What he's saying is that code similar to the *second* version
fails. That's what all the commotion is about over there. This
simple example obviously works, yet in his more complicated code
base something goes wrong.
More information about the Digitalmars-d-learn
mailing list