On 19 Jun 2006 18:06:25 -0700,

(E-Mail Removed) wrote in comp.lang.c:

> Hi,

>

> I have a function which compares two unsigned ints and returns their

> difference in order to establish which is the greater of the two.

>

> int Compare(unsigned int time_left, unsigned int time_right)

> {

> return (time_left - time_right);

> }

>

> usage -

>

> if( Compare(time_left, time_right) > 0)

> // the time has come.

>

> The problem is that when time_left is 5 and time_right is 10, I get -5,

> but if time_left is 5 and time_right is 0xc0000005 (a number greater

> than 5) I get a positive value when I wish to get a negitive one.

>

> I understand why I get this positive value - because the negaitve bit

> is set in time_right, but how can I change my code so that I get the

> desired results.

>

> Thanks for your help,
What happens if the difference is has greater magnitude that a signed

int can hold? If one of the values is UINT_MAX and the other is 0,

the difference between them is either positive or negative UINT_MAX,

and that won't fit in a signed int on any platform you are ever likely

to see in your career.

Still assuming it fits (untested):

int Compare(unsigned int time_left, unsigned int time_right)

{

int result;

if (time_left >= time_right)

{

result = time_left - time_right;

}

else

{

result = -(int)(time_right - time_left);

}

return result;

}

--

Jack Klein

Home:

http://JK-Technology.Com
FAQs for

comp.lang.c

http://c-faq.com/
comp.lang.c++

http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++

http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html