PRB: C2361: Initialization of "i" Is Skipped by "Default"

ID: Q87013


The information in this article applies to:
  • The Microsoft C/C++ Compiler (CL.EXE),
    • Microsoft C/C++ for MS-DOS, version 7.0
    • Microsoft Visual C++ for Windows, 16-bit edition, versions 1.0, 1.5, 1.51, 1.52
    • Microsoft Visual C++, 32-bit Editions, versions 1.0, 2.0, 2.1, 4.0, 4.1, 4.2, 5.0


SYMPTOMS

An attempt to compile the Sample Code below as a C++ file with one of the compilers listed above will fail and generate the following message:

error C2361: Initialization of 'i' is skipped by 'default' label


CAUSE

This error occurs because the "case" and "default" labels do not limit scope; instead, each one is a structured goto and suffers the same limitations with respect to control flow. In the example below, the symbol "i" remains in scope in subsequent "case" clauses. However, if the flow of control is transferred to these clauses, the object was not initialized. The C++ language requires determining possible control flow errors through a static analysis of the code.


RESOLUTION

Two possible solutions are:

  • Use braces to create a block that contains the initialization statement so the variable "i" is in scope only for the case that uses the variable. The resulting statement resembles the following:
    
       case 2 :
       {
          int i = 1;
          break;
       } 


  • -or-
  • Instead of initializing "i" in one step, declare the variable and assign it a value in two separate steps, as follows:
    
          case 2 :
            int i;
            i = 1;
            break; 
    This technique works because the flow of control cannot skip the initialization.



MORE INFORMATION

The compiler-generated error described above is correct. This behavior is required by the C++ language.

Sample Code


/* Compile options needed: /Tp
*/ 

int var;

void main()
{
   switch (var)
   {
      case 1:
         // do something
         break;

      case 2:
         int i = 1;
         break;

      default:
         // do something else
         break;
   }
} 

Additional query words: 8.00 8.00c 9.00 9.10

Keywords : kbCompiler kbCPPonly kbVC100 kbVC150 kbVC151 kbVC152 kbVC200 kbVC210 kbVC400 kbVC410 kbVC420 kbVC500
Version : MS-DOS:7.0;WINDOWS:1.0,1.5,1.51,1.52;WINDOWS NT:1.0,2.0,2.1,4.0,4.1,4.2,5.0
Platform : MS-DOS NT WINDOWS
Issue type : kbprb


Last Reviewed: July 6, 1999
© 2000 Microsoft Corporation. All rights reserved. Terms of Use.