简体   繁体   中英

goto produces an error "bypassing initialization"

I'm trying to use labels in my project but when I jump over a set of instructions using goto to transfer control to another section of the code, I get this error that says: transfer control bypasses initialization of (certain variables) .

This is the code that produces the error:

    goto label1;

    label00:
    int a = 0;//the compiler can't let me skip this line
    int b; // but this line is fine to skip over
    b = 0; //because i initialize it here instead of doing it like the a variable

    label1:
    //other instructions

as you can see I have two variables initialized but one of them is defined then initialized but the other one is defined and initialized at the same line.

The one that is defined and initialized at the same line variable a does not produce an error when skipped over, but the other one does.

I'm using VS2019 to compile this code. I think this should not throw an error at all and the compiler should give you a warning so that you know you're skipping something in both cases a and b initializations .

Is there any solution to this like disabling something in the settings?

I don't want to declare my variables then initialized them when using labels.

I think this should not throw an error at all

The compiler is free to refuse to compile ill-formed programs.

Is there any solution to this

Solutions:

  1. Don't initialise a .
  2. Declare a before the jump.
  3. Declare a after the label.
  4. Don't use the goto (my favourite).
  5. Limit the scope of a by declaring it within a block statement that ends before the label.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM