Go to the first, previous, next, last section, table of contents.

g++ objects to a declaration in a case statement

"The compiler objects to my declaring a variable in one of the branches of a case statement. Earlier versions used to accept this code. Why?"

The draft standard does not allow a goto or a jump to a case label to skip over an initialization of a variable or a class object. For example:

switch ( i ) {
  case 1:
    Object obj(0);
        ...
    break;
  case 2:
	...
    break;
}    

The reason is that obj is also in scope in the rest of the switch statement.

As of version 2.7.0, the compiler will object that the jump to the second case level crosses the initialization of obj. Older compiler versions would object only if class Object has a destructor. In either case, the solution is to add a set of curly braces around the case branch:

  case 1:
    {
       Object obj(0);
        ...
       break;
    }

Go to the first, previous, next, last section, table of contents.