Posted by: billconan | September 12, 2006

无符号的整数好危险

最近经常会犯一些比较低级的错误,比如无符号的整数问题。如果一个变量不可能取负值我就习惯声明成无符号类型,比如说数组的下标。这样做主要是为了完全利用32位字长。但是也会构成些隐患。比如这个就不会循环:

for(size_t i=vectorCount;i>-1;–i)
{

}

而这个循环了很多遍,如果count为0的话:

for(size_t i=count-1;i>0;–i)
{

}

这个要经常注意了,很容易犯。

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: