Goto skips declaration
Michelle Long
HappyDance321 at gmail.com
Sat Nov 3 03:52:12 UTC 2018
On Tuesday, 30 October 2018 at 23:31:46 UTC, luckoverthere wrote:
> On Tuesday, 30 October 2018 at 21:21:22 UTC, Michelle Long
> wrote:
>>
>> You take examples WAY to literal. Sheesh, do you really think
>> life is that simple? Do you need every detail spelled out for
>> things to make sense?
>>
>> foreach(x; Y)
>> {
>> if (something or another which I won't spell out no matter
>> how much you cry)
>> goto Q; // compiler complains here about x
>> int x;
>> }
>> Q:
>>
>> There is no reason why the compiler should have a problem with
>> this.. the fact that using brackets around int x; satisfies
>> the compiler proves this.
>
>
> struct Magic
> {
> ~Magic()
> {
> writeln("blah");
> }
> ]
>
> void test()
> {
> if(cond)
> goto Y;
>
> Magic magic;
>
> Y:
> writeln("stuff");
>
> // calls ~Magic();
> }
>
> You'd need a bunch of extra information to know what is and
> wasn't actually declared and initialized.
>
> "Putting brackets around it proves it".
>
> void test()
> {
> if(cond)
> goto Y;
>
> {
> Magic magic;
>
> // calls ~Magic();
> }
>
> Y:
> writeln("stuff");
>
> }
>
> There is no more conflict with brackets, yes. But expecting the
> compiler to do this changes the behavior of the code. Sure if
> there's no destructor it could work around it, but it would
> complicated code generation. Adding a bunch of time looking for
> these circumstances.
>
> It's just not worth it, use brackets like you are now or move
> the declarations of your variables up to the top of the scope
> before any gotos. Pretty simple workarounds.
You are not understanding the problem. The goto must be in the
same scope as the local variable:
{
goto Y;
int x;
}
Y:
The compiler will complain(I'm doing it in a foreach loop) that x
is skipped!!!
Do you understand?
The goto will always bypass x being declared so it doesn't
matter. The compiler may optimize out the simple case above, but
that is irrelevant to the problem.
The problem is simple: The compiler thinks that the declared
variables are used after the goto but it is impossible since the
goto skips out of the block and the local variables cease to
exist.
The compiler treats the problem as if it is
{
goto Y:
int x;
Y:
}
and that is a totally different problem. They are not the same
but the compiler treats them the same.
In the second case the goto does skip over the declaration, in
the first case it does not. In the second case it is a problem
but in the first case it cannot be.
Again, adding the brackets proves it.
More information about the Digitalmars-d
mailing list