PRB:Bad Code Generated for "a+b == a" FP Comparison Expression

ID Number: Q68559

6.00 6.00a 6.00ax 7.00 | 6.00 6.00a

MS-DOS | OS/2

Summary:

SYMPTOMS

The Microsoft C Compiler versions 6.0, 6.0a, 6.0ax, and C/C++ version

7.0 will perform an optimization on expressions of the form

"a+b == a" if a and b are floating-point variables (double or float

type).

RESOLUTION

This is expected behavior for the compiler. The proper code is

generated by compiling with the /Op option, which directs the

compiler to use consistent floating-point calculations. If this is

not a viable option, one of the following will work around the

situation:

- Enclose the expression "a+b" in parentheses.

- Make the variables a and b integers, if applicable.

- Compile with the /qc (quick compile) option.

More Information:

Sample code with floating-point expressions of the form "a+b == a" was

compiled with optimization disabled (/Od) and the first few lines of

the resulting assembly listing follows:

; double a,b;

; if (a+b == a) ;

*** 00000b 9b d9 ee fldz

*** 00000e 9b dc 16 00 00 fcom QWORD PTR _b

*** 000013 9b dd d8 fstp ST(0)

*** (lines deleted)

; if ((a+b) == a) ;

*** 000025 9b dd 06 00 00 fld QWORD PTR _b

*** 00002a 9b dc 06 00 00 fadd QWORD PTR _a

*** 00002f 9b dc 16 00 00 fcom QWORD PTR _a

*** 000034 9b dd d8 fstp ST(0)

*** (lines deleted)

Note that the first expression gets optimized to compare variable b to

zero, rather than comparing a+b to a. In the second expression, a+b is

correctly compared to a.

Compiling with the /Op option generates the correct code in both

cases. The expression (a+b == a) might be used with floating point

numbers to detect when b is negligibly small in relation to a.