PRB: Dividing Negative Integers May Give Positive Results

ID Number: Q67740

5.10 6.00 6.00a 6.00ax | 5.10 6.00 6.00a

MS-DOS | OS/2

buglist5.10 buglist6.00 buglist6.00a buglist6.00ax fixlist7.00

Summary:

SYMPTOMS

In Microsoft C versions 5.1, 6.0, 6.0a, and 6.0ax, in some

situations, dividing a negative integer by a positive integer may

give positive results. For example, when the sample code below is

compiled with the /Od option, both printf() statements will generate

positive answers.

CAUSE

When these calculations are performed, the sign bit is lost. The

output is incorrect for the first printf() statement when -32768 is

being divided by a power of 2 (for example, 4,8,16,32,64,...16384).

RESOLUTION

Workarounds for the first printf() statement are:

1. Compile without the /Od option.

2. Compile with the /qc option.

With the second printf(), the value (num2 & 0xfff0) must be typecast

to an integer or separated into another statement. For example,

printf(" %d ", (int)(num2 & 0xfff0) / 16);

-or-

num3 = num2 & 0xfff0;

printf(" %d ", num3 / 16);

STATUS

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

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

7.0.

More Information:

Sample Code

-----------

void func1(void)

{

int num1 = -32768,

num2 = -32751;

printf(" %d ", num1 / 16);

printf(" %d ", (num2 & 0xfff0) / 16);

}