PRB: C2361: Initialization of "i" Is Skipped by "Default"ID: Q87013
|
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
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.
Two possible solutions are:
case 2 :
{
int i = 1;
break;
}
-or-
case 2 :
int i;
i = 1;
break;
This technique works because the flow of control cannot skip the
initialization.The compiler-generated error described above is correct. This behavior is required by the C++ language.
/* 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 5, 1999