Switch Statement May Execute Improperly with long Values

ID Number: Q74833

6.00 6.00a 6.00ax | 6.00 6.00a

MS-DOS | OS/2

buglist6.00 buglist6.00a buglist6.00ax fixlist7.00

Summary:

In some cases, switch statements compiled with Microsoft C version

6.0, 6.0a, or 6.0ax may behave improperly if the switch expression is

a long value. Instead of executing the proper case, the default case

is executed and incorrect program flow results.

More Information:

The sample code below demonstrates this problem. When the switch

expression evaluates to particular values, the default case is

incorrectly executed. To work around this problem, replace the switch

statement with a series of if-else constructs, or compile with the /qc

(quick compile) option.

Microsoft has confirmed this to be a problem in C versions 6.0, 6.0a,

and 6.0ax. This problem was corrected in C/C++ version 7.0.

Sample Code

-----------

/* Compile options needed: none

*/

#include <stdio.h>

int switch_func(unsigned long val);

void main(void)

{

if ( switch_func(0x000000) == 0 )

printf("switch failed on 0x000000:\n");

if ( switch_func(0x996600) == 0 )

printf("switch failed on 0x996600:\n");

if ( switch_func(0xbfbfbf) == 0 )

printf("switch failed on 0xbfbfbf:\n");

if ( switch_func(0x9f9f9f) == 0 )

printf("switch failed on 0x9f9f9f:\n");

if ( switch_func(0xdf2020) == 0 )

printf("switch failed on 0xdf2020:\n");

if ( switch_func(0xffffff) == 0 )

printf("switch failed on 0xffffff:\n");

if ( switch_func(0x0000ff) == 0 )

printf("switch failed on 0x0000ff:\n");

if ( switch_func(0xffff40) == 0 )

printf("switch failed on 0xffff40:\n");

if ( switch_func(0x20ffff) == 0 )

printf("switch failed on 0x20ffff:\n");

if ( switch_func(0x40ff40) == 0 )

printf("switch failed on 0x40ff40:\n");

if ( switch_func(0x9f009f) == 0 )

printf("switch failed on 0x9f009f:\n");

if ( switch_func(0x003070) == 0 )

printf("switch failed on 0x003070:\n");

if ( switch_func(0x7f7f00) == 0 )

printf("switch failed on 0x7f7f00:\n");

if ( switch_func(0x007f00) == 0 )

printf("switch failed on 0x007f00:\n");

if ( switch_func(0x7f7faf) == 0 )

printf("switch failed on 0x7f7faf:\n");

}

int switch_func(unsigned long val)

{

switch(val)

{

case 0x000000:

case 0x996600:

case 0xbfbfbf:

case 0x9f9f9f:

case 0xdf2020:

case 0xffffff: // fails here

case 0x0000ff:

case 0xffff40:

case 0x20ffff:

case 0x40ff40:

case 0x9f009f:

case 0x003070:

case 0x7f7f00:

case 0x007f00:

case 0x7f7faf: // fails here

return 1;

default:

return 0;

}

}