On May 12, 3:58=A0pm, Bart <b...@[EMAIL PROTECTED]
> wrote:
> On May 12, 11:18=A0pm, fred.l.kleinschm...@[EMAIL PROTECTED]
wrote:
>
> > If one knows that x and y are unsigned integers (of unknown size -
> > they may be short, int, long, long long), what is the most ****table
> > way to determine their difference?
>
> > If x is smaller than y, then x-y is negative.
>
> > A naive approach is
> > =A0 =A0if ( x > y ) {
> > =A0 =A0 =A0 ...
> > =A0 =A0}
>
> > but a compiler may code (x>y) as =A0(x-y > 0).
>
> What do you mean by difference?
>
> If you mean x-y, then this will give strange results when x<y (it
> can't be negative).
>
> If you mean max(x,y)-min(x,y) then your 'naive' approach will likely
> work well.
>
The problem came up on a Unix platform, where some code was trying
to check for a double-click. Each time button1 is clicked, it checks
the time with the previous time it was clicked; if the difference is
small enough, a double-click is assumed.
The times are stored in a variable of type Time, defined as
an unsigned int on some platforms, unsigned long on others, storing
clock time in milliseconds.
For an unsigned int, the value will wrap every 47 days. The original
code was
if ( (newtime - oldtime) < doubleclicktime ) {
/* perform double-click action */
}
That code is unsafe: as oldtime approaches UINT_MAX, the risk
is that newtime might occur after time wraps, thus might be
a small integer, and (newtime - oldtime) is mathematically
negative.
Since others have said that the compiler is obliged to
perform the if-test properly, my solution is
if ( t2 > t1 ) {
delta =3D t2 - t1;
}
else {
delta =3D (UINT_MAX - t1) + t2 + 1;
}
--
Fred Kleinschmidt


|