semantics of arith comparisons

Stephen Clamage steve at taumet.com
Thu Feb 7 03:33:51 AEST 1991


matsc at sics.se (Mats Carlsson) writes:

>In the following program, the functions test1 and test2 are meant to
>be equivalent.  The only difference is that a variable is introduced in
>test2 to temporarily hold a value. ... [example shrunk to save space]

>test1(int i) {
>  if (i + 0x40000000 >= 0) return 1;
>  else return 0;
>}

>test2(int i) {
>  int j = i + 0x40000000;
>  if (j >= 0) return 1;
>  else return 0;
>}

The temp you introduced is NOT the same type as the expression, and that
is the reason for the difference.

Hex constants are of type unsigned int, and so in test1 the value of
(i+0x40000000) is type unsigned int.  (When you add an int and an unsigned
int, the result is type unsigned int.) In the comparison to 0, the
top bit is a magnitude bit, not a sign bit.

In test2, you store the result of (i+0x40000000) in an int.  This
preserves the bit pattern, but the top bit is now treated as a sign bit
in the comparison.
-- 

Steve Clamage, TauMetric Corp, steve at taumet.com



More information about the Comp.lang.c mailing list