Numeric comparisons

Walter Bright bright at dataio.UUCP
Tue Sep 3 07:11:37 AEST 1985


In article <693 at terak.UUCP> doug at terak.UUCP (Doug Pardee) writes:
>Compiler writers note -- a comparison is not "just a subtract".
>For example:
>
>#define NBITS 16
>/* NBITS is number of bits in an integer */
>   int a, b;
>   a = 3 << (NBITS-3);  /* 24576 for NBITS=16 */
>   b = -a;
>   if (a>b)
>      printf("Comparison was done by bit-wise comparison\n");
>   else
>      printf("Comparison was done by subtraction\n");   /* WRONG */
>A compiler would have had to generate extra code to test for Overflow
>in order to get the correct result.

I disagree. A comparison is a subtract with the result thrown away. The
trick is to select the correct conditional branch instruction afterwards,
depending on whether a signed or unsigned comparison was done. The case
you labeled as WRONG is wrong, a compiler that did that would have a bug,
but not for the reasons you mentioned. If a or b was declared as unsigned,
that case would be correct. No additional code is required to test for
Overflow, that is handled by using the correct conditional branch, even
if a subtract instruction was generated.



More information about the Comp.lang.c mailing list