Home c++ Initialization error due to case label

Initialization error due to case label [duplicate]

Author

Date

Category

I just can’t figure out what the error is in the code. For example, if I write like this:

fstream f ("data.txt");
switch (choosing)
{
case 1:
    f & gt; & gt; size & gt; & gt; x;
    break;
case 2:
  break;
}

Everything works fine, but if I write:

switch (choosing)
{
case 1:
    fstream f ("data.txt");
    f & gt; & gt; size & gt; & gt; x;
    break;
case 2:
  break;
}

I’ll get an error like this:

Error C2360 skipping initialization "f" due to label "case" Train d: \ C++ projects \ train \ train \ source.cpp 71

The question is, what’s wrong? After all, in fact, I just move the initialization of the file variable from inside the case to the outside?


Answer 1, authority 100%

The fact is that in C++ the switch / case construct is a masked goto and case blocks are not create scopes. You have something like this going on:

if (1 == choosing)
{
  goto mark1;
}
if (2 == choosing)
{
  goto mark2;
}
{
  mark1:
  fstream f ("data.txt");
  f & gt; & gt; size & gt; & gt; x;
  goto ending;
  mark2:
  // if choosing is 2, then we get here, skipping the initialization of f
  goto ending;
}
ending :;

Accordingly, for each case , you should manually create a new scope:

switch (choosing)
{
  case 1:
  {
    fstream f ("data.txt");
    f & gt; & gt; size & gt; & gt; x;
  }
break;
  case 2:
  {
  }
  break;
}

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions