Saturday, June 13, 2009

Comparison against overflow

Time variables are subject to overflow. So, the comparison statement as follow will return incorrect result if t1 has overflowed and t2 has not overflowed.

unsigned long t1, t2; if (t1 > t2) printf("t1 > t2");

The code as follow can be used to deal with the above issue.

unsigned long t1, t2; if ((long)(t1 - t2) > 0) printf("t1 > t2");

Suppose sizeof(unsigned long) = 4, and t1 < t2, the result of t1 - t2 under the unsigned semantics is (0x100000000 + t1 - t2), because of borrow, if the result < 0x80000000, in signed semantics and complemental code, the result is positive.

No comments: