PRB: Variables with Local Scope to Switch Won't Be Initialized

ID Number: Q73850

5.10 6.00 6.00a 6.00ax 7.00 | 5.10 6.00 6.00a

MS-DOS | OS/2

Summary:

SYMPTOMS

In Microsoft C versions 5.1, 6.0, 6.0a, 6.0ax, and C/C++ 7.0,

variables may be declared as local to a switch statement by

defining them within the braces that make up the switch. They

then have visibility and life for the duration of the switch

statement. However, because of the design of a switch block,

they will not be initialized when declared unless the variable

is static or is declared after a case label.

RESOLUTION

If you must declare an initialized variable that is local to the

switch statement and transient in duration, use brackets before and

after the switch and place the declaration outside the switch

statement.

More Information:

The ANSI Standard (Section 3.6.4.2) states:

A "switch" statement causes control to jump to, into, or past

the statement that is the switch body, depending on the value

of a controlling expression, and on the presence of a "default"

label and the values of any "case" labels on or in the switch

body. A "case" or "default" label is accessible only within the

closest enclosing "switch" statement.

The integral promotions are performed on the controlling

expression. The constant expression in each "case" label is

converted to the promoted type of the controlling expression.

If a converted value matches that of the promoted controlling

expression, control jumps to the statement following the

matched "case" label. Otherwise, if there is a "default" label,

control jumps to the labeled statement. If no converted case

constant expression matches and there is no default label, no

part of the switch body is executed.

The sample code below illustrates this. To have the variable

local_int initialized to the correct value (5 in this case), you have

two choices. If it must be an automatic variable, you have to either

declare it outside the switch statement (with parentheses to limit

scope) or after each case that you wish to use it. If the variable

does not have to be automatic, merely declare it as static.

Sample Code

-----------

/* Compile options needed: none

*/

int _cdecl printf(const char *, ...);

void switch_func(int);

int main(void);

int rc = 0;

int main(void)

{

switch_func(100);

if (rc)

printf("Failed\n");

else

printf("Passed\n");

return(rc);

}

void switch_func(int param)

{

switch (param)

{

int local_int = 5;

case 100:

local_int+=5;

rc = (local_int == 10 ? 0 : 1);

break;

default:

break;

}

}

Additional reference words: QuickC 2.0 2.00 2.01 2.5 2.50 2.51 6.0

6.00 6.0a 6.00a 6.0ax 6.00ax 7.00