Microsoft KB Archive/86479

= INFO: Initializing in a Loop Within a Case Statement =

Article ID: 86479

Article Last Modified on 7/5/2005

-

APPLIES TO


 * Microsoft Visual C++ 1.0 Professional Edition
 * Microsoft Visual C++ 1.5 Professional Edition
 * Microsoft Visual C++ 2.0 Professional Edition
 * Microsoft Visual C++ 4.0 Standard Edition
 * Microsoft Visual C++ 5.0 Enterprise Edition
 * Microsoft Visual C++ 5.0 Professional Edition

-



This article was previously published under Q86479



SUMMARY
In the products listed above, the following errors can occur when you define a variable in a loop that is within a case statement. The following error occurs when &quot;default&quot; is the next case:

C2361 Initialization of 'x' is skipped by 'default' label

When default is not next, the following error appears:

C2360 Initialization of 'x' is skipped by 'case' label

A similar error also occurs when a goto is before the loop:

C2362 Initialization of 'x' is skipped by 'goto label name'



MORE INFORMATION
In the two samples below, it can be seen that the variable is initialized when it is declared. The errors are generated because the scope of the variable, when it is defined and initialized, is in the same scope as the case label or the goto label. Thus, there is a chance that the initialization will not occur. There are ways to ensure that the initialization is performed:  Enclose the for loop in &quot;{}&quot; (curly braces). This will cause the for loop to be in a different scope than the case and goto labels.

-or-

 Define the loop variable right before entering the loop. This works only for simple types, not for user-defined types.

-or-

 Define the variable without initializing it. Any assignments made to that variable after its definition are considered assignments, not initializations.

Sample Code 1

 * 1) include 

/* Compile Options needed: none.

void main( void ) { int var;

switch( var ) {   case 1 : for (int i = 0; i < 3; ++i) {               printf(&quot;In loop&quot;); }            break;

case 2 : printf(&quot;Case 2&quot;);           // C2360 break;

default : printf(&quot;Default&quot;);         // C2361 break; } }

Sample Code 2

 * 1) include 

/* Compile options needed: none.

void main (void) {  goto label;

int var = 0;

label:;                               // C2362 }

Keywords: kberrmsg kbinfo kblangcpp kbcode KB86479

-

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

© Microsoft Corporation. All rights reserved.