Friday, March 23, 2007

C++ note: be careful with unsigned

I just made a mistake with an unsigned integer. It took me nearly an hour to debug, just to find that the subtle bug is caused by this:

if (a<b-2) ...

a = 0 b = 1

b is an unsigned integer.

The reason is that b-2 is interpreted as unsigned integer, and therefore the predicate wrong. The conclusion is that we should avoid using many minuses for unsigned.

if (a+2<b) is the solution for this problem

No comments: