Numeric comparisons

Doug Pardee doug at terak.UUCP
Fri Sep 20 10:38:45 AEST 1985


> 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.

Watch my lips!  A signed comparison is *not* a subtract with the result
thrown away.  Write that down so you don't forget it.

I offer another example... take an 8-bit machine, both for simplicity
and because the 8080A/Z80/6502 all did compares via subtraction.  If you
compare the A register with a decimal 40 on any of those CPUs, you will
get the following results:
  A=+41: Ovf=0  N=0  C=no borrow (1 on 6502, 0 on 8080A/Z80)
  A=+39: Ovf=0  N=1  C=borrow
  A=-40: Ovf=0  N=1  C=no borrow
  A=-90: Ovf=1  N=0  C=no borrow

The situation is even worse if you don't know whether the comparison
value (40 in this example) is positive or negative.

> 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.

There is *no* conditional branch on those CPUs which will reliably
select high versus low on a signed comparison.  The only way to handle
this is with a network of branches, which do normal branching if no
Overflow, and opposite branching if the Overflow bit is set.  Lord knows
I've written enough of 'em.

Fortunately, the more modern CPU chips are designed with a proper
compare instruction which does bit-wise comparison instead of
subtraction.  All I ask is that the compiler writers *use* those
instructions the way they were intended, instead of substituting a
subtraction.  <Fortunately, the NS32000 CPUs don't provide status bits
(except carry) on subtraction, so the compiler writer is forced to use
the bit-wise compare instruction>.
-- 
Doug Pardee -- CalComp -- {calcom1,savax,seismo,decvax,ihnp4}!terak!doug



More information about the Comp.lang.c mailing list