Microsoft KB Archive/87013

= PRB: C2361: Initialization of &quot;i&quot; Is Skipped by &quot;Default&quot; =

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 &quot;case&quot; and &quot;default&quot; 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 &quot;i&quot; remains in scope in subsequent &quot;case&quot; 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 &quot;i&quot; is in scope only for the case that uses the variable. The resulting statement resembles the following:   case 2 : {     int i = 1; break; }   Instead of initializing &quot;i&quot; 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

Issue type : kbprb

Technology :

Last Reviewed: July 30, 2001

-

[mailto:MSDN@MICROSOFT.COM Send feedback to Microsoft]

© 2002 Microsoft Corporation. All rights reserved.