On Tue, 13 May 2008 22:55:41 +0200, Øyvind Røtvold wrote:
> writes:
>> On May 12, 3:58Â*pm, Bart <b...@freeuk.com> wrote:
> [ snip ]
>> 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:
>
> No.
>
>> as oldtime approaches UINT_MAX, the risk is that newtime might occur
>> after time wraps, thus might be a small integer,
>
> Yes.
>
>> and (newtime - oldtime) is mathematically negative.
>
> If newtime and oldtime are of the same unsigned type, the result will
> never be negative, and (newtime - oldtime) will be the correct time
> difference even when there's a wrap.
If newtime and oldtime are of the same unsigned type, *and that unsigned
type is unsigned int or wider*, then yes. It is unsigned int here,
apparently, so then it is safe, but it's not safe with smaller unsigned
types. If they were of type unsigned short, for example, it's very well
possible for newtime - oldtime to produce a negative result, because
newtime and oldtime will be promoted, typically to signed int, before any
subtraction takes place.