Is this a bug? +goto

Jonathan M Davis newsgroup.d at jmdavisprog.com
Tue Nov 6 05:46:40 UTC 2018


On Monday, November 5, 2018 7:55:46 PM MST MatheusBN via Digitalmars-d-learn 
wrote:
> On Tuesday, 6 November 2018 at 01:55:04 UTC, Jonathan M Davis
>
> wrote:
> >> 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.
>
> That is exactly my point.
>
> Since "x" it's skipped and never used, it shouldn't just be a
> warning (unreachable code) instead of an error?
>
> I'm trying to understand why/when such code could give any
> problem.
>
> On the other hand if the code were:
>
> {
>     goto Q:
>     int x;
>
>     Q:
>     x = 10; // <- Now you are accessing an uninitialized variable.
> }
>
> Then I think an error would be ok.

D tries to _very_ little with code flow analysis, because once you start
having to do much with it, odds are that the compiler implementation is
going to get it wrong. As such, any feature that involves code flow analysis
in D tends to be _very_ simple. So, D avoids the issue here by saying that
you cannot skip the initialization of a variable with goto. The compiler is
not going to do the complicated logic of keeping track of where you access
the variable in relation to the goto. That's exactly the sort of thing that
might be obvious in the simple case but is highly likely to be buggy in more
complex code. Code such as

{
    goto Q;
    int x;
}
Q:

or

{
    if(foo)
        goto Q;
    int x;
}
Q:


is fine, because the compiler can trivially see that it is impossible for x
to be used after it's been skipped, whereas with something like

goto Q;
int x;
Q:

the compiler has to do much more complicated analysis of what the code is
doing in order to determine that, and when the code isn't trivial, that can
get _really_ complicated.

You could argue that it would be nicer if the language required that the
compiler be smarter about it, but by having the compiler be stupid, it
reduces the risk of compiler bugs, and most people would consider code doing
much with gotos like this to be poor code anyway. Most of the cases where
goto is reasonable tend to be using goto from inside braces already, because
it tends to be used as a way to more efficiently exit deeply nested code.
And with D's labeled break and continue, the need for using goto outside of
switch statements also tends to be lower than it is in C/C++.

- Jonathan M Davis





More information about the Digitalmars-d-learn mailing list