Is this a bug? +goto
Jonathan M Davis
newsgroup.d at jmdavisprog.com
Tue Nov 6 01:55:04 UTC 2018
On Monday, November 5, 2018 5:33:56 PM MST MatheusBN via Digitalmars-d-learn
wrote:
> On Tuesday, 6 November 2018 at 00:14:26 UTC, Jonathan M Davis
>
> wrote:
> > On Monday, November 5, 2018 4:54:59 PM MST MatheusBN via
> >
> > Digitalmars-d-learn 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?
> >
> > All the spec says on the matter is that
> >
> > "It is illegal for a GotoStatement to be used to skip
> > initializations."
> >
> > https://dlang.org/spec/statement.html#goto-statement
> >
> > In the first case, x exists at the label Q, and its
> > initialization was skipped, so it's clearly illegal. However,
> > in the second case, because of the braces, x does _not_ exist
>
> Just to be clear, when you say "x exists at the label Q", you
> mean at the same scope, right?
The scope that x was at is over at the label Q. So, x doesn't exist at the
label Q. It has no address at that point. It's not on the stack. It doesn't
exist in any sense other than the fact that it happens to be in the source
code above it. In fact, the line with x never even ran, so x _never_
existed.
> That's interesting but a bit confusing isn't?
I don't see why.
{
goto Q;
int x;
}
Q:
is basically the same thing as
while(1)
{
break;
int x;
}
The same thing happens in both cases.
> And I found a bit strange that in such code, since "x" is never
> used, why it isn't skipped.
It's skipped right over. The goto jumps out of the scope, and the line with
int x;
is never run. In fact, if you compile with -w or -wi, the compiler will give
you a warning about unreachable code.
> I know it's another language but in C at least in GCC there is no
> error over such code, so that's my confusion.
C is a different language, and it's one that generally doesn't care much
about safety. It allows all kinds of horrible things that cause bugs. The
folks behind D (and the folks behind _most_ languages since C/C++) tend to
prefer a greater degree of safety than C provides.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list