0

I've come across an error that I thought should have been a warning:

char* p;

int main()
{

    if (p) goto continue_func;

    int a = 3;


continue_func:
    int b = 2;
}   

The error I get:

initialization of 'a' is skipped by 'goto continue_func'

transfer of control bypasses initialization of:

I don't see why this is illegal. If the case had been something like this:

char* p;

int main()
{

    if (p) goto continue_func;

    int a = 3;


continue_func:
    int b = 2;
    int c = a + b;
    std::cout << c;
}

Then I understand that a is being used. But in the first example it's not. Is this truly illegal C++, and why?

Zebrafish
  • 11,682
  • 3
  • 43
  • 119
  • 1
    Pro tip: Don't use `goto`. There are very very few cases where it is actually needed. – NathanOliver Feb 07 '23 at 21:54
  • Goto should have been removed from the language 30 years ago. – Joseph Larson Feb 07 '23 at 21:55
  • 3
    The compiler told you the reason: the code could skip the initialization of `a`. The fact that `a` isn’t used doesn’t change that. Consider a variable whose type has a destructor… – Pete Becker Feb 07 '23 at 21:57
  • its illegal because the standard says it is. are you really writing such code? if so, stop doing so, otherwise don't worry about it. – Neil Butterworth Feb 07 '23 at 22:03
  • `int a; a = 3;` would allow this code to compile without error. You are getting an error because you are promising that this variable is initialized, and then breaking that promise. – Drew Dormann Feb 07 '23 at 22:28

0 Answers0