PRB: Variables with Local Scope to Switch Won't Be InitializedLast reviewed: July 24, 1997Article ID: Q73850 |
The information in this article applies to:
SYMPTOMSIn Microsoft C, 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.
RESOLUTIONIf 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 INFORMATIONThe 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. Compiling the sample code below and runnning the resultant executable demonstrates this problem. The following text will be output:
local_int NOT initializedThere are three options available to ensure that the variable local_int is initialized to the correct value (5 in this case):
|
Keywords : CLngIss kbfasttip
© 1998 Microsoft Corporation. All rights reserved. Terms of Use. |