3

When compiling the following code it provides me with two errors; "jump to case label" and "crosses initialization of std::ofstream SaveLogin". I am currently using codeblocks with the gnu gcc compiler.

switch(choice) {
  case 1:
    // login
  case 2:
    // register
    ofstream SaveLogin;
    break;
  case 3:
    // reset password

;}

Thanks for viewing my question-EDIT: my question was flagged as a duplicate of another question but the question specified did not entirely conclude my problem. This post is specifically about my problem although I hope it can hope any other people who are having the same problem

  • In case it's not clear: those are two lines of the same error. The problem is that a jump to a `case` label crosses the initialisation of an object. – Angew is no longer proud of SO Aug 12 '16 at 12:23
  • Possible duplicate of [What are the signs of crosses initialization?](http://stackoverflow.com/questions/2392655/what-are-the-signs-of-crosses-initialization) – underscore_d Aug 12 '16 at 12:26

2 Answers2

2

The compiler is correct: C++ does not allow you to skip over a variable declaration in the same scope. goto is similarly restricted.

If you need SaveLogin for all cases then declare it above the switch. If you only need it for case 2 then use scope blocks:

case 2 /*not directly relevant but there's no need for the parentheses*/:
{
    // register
    ofstream SaveLogin; /*ToDo - more logic here unless it's contained
                         fully within construction and destruction*/
    break;
}
case 3:
Bathsheba
  • 231,907
  • 34
  • 361
  • 483
1

Here's a small change to the code that should illustrate the problem:

switch(choice) {
  case 1:
    // login
  case 2:
    // register
    ofstream SaveLogin;
    break;
  case 3:
    // reset password
    SaveLogin << "whatever\n"; // added code
;}

That last line would be legal, because SaveLogin is in scope, but it would get executed only as part of case 3, which skips the initialization of SaveLogin. So the rule is that a jump (switch or goto) can't skip an initializer. One possibility, as @Bathsheba mentions, is to put the definition of SaveLogin above the case statement. Another possibility is to limit the scope of SaveLogin so that the jump doesn't bypass it:

case 2:
    {
    ofstream SaveLogin;
    break;
    }
case 3:

With the curly braces, SaveLogin is not in scope at case 3 and the problem has gone away.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165