关于signed和unsigned的隐秘bug

看看如下代码:

 

vector<int> vec;

int i = 0;

if ( i > vec.size() - 1)

{

.....

}

 

if 判断句是否为真呢??

似乎vec.szie()为0,而 0 -1 = -1, 所以 0 > vec.size()-1

 

其实不然,vec.size()返回的是size_type类型的值,而vector中size_type通常为unsigned

所以vec.size() - 1 = (unsigned)0 - (unsigned)1 = (unsigned)-1 = 0xfffffff> 0

而且i是signed int, 而vect.size() - 1是usigned int. signed碰上unsigned会被转为同类型的unsigned.

 

结论,对于signed和unsigned混用的情况,千万要小心.通常vc会对这些signed和unsigned转换会提出警告,这个一定要重视

你可能感兴趣的:(关于signed和unsigned的隐秘bug)