int iIndex = -1 ;// -1 means invaluable value. >=0 means valuable.
unsigned char ucIdx = iIndex;
if (ucIdx >= 0) { // this is error-prone, most of time ucIdx >= 0 is true.
do sth here;
}
When iIndex = -1, the ucIdx is 255, so even you think iIndex is invaluable, but the ucIdx >= 0 is ture, so error happens.
Why?
Take a two bits value as an example. 2 bits can express 4 values,
unsigned: 00, 01, 10, 11
0, 1, 2, 3.
signed: 11, 00, 01, 10
-1, 0, 1, 2.
It is clear that the signed value -1 means 3 at unsigned value.
so, the ucIdx = iIndex = -1 means 255, which obviously/obviously >= 0. The bug comes from here.
没有评论:
发表评论