问题描述
我始终使用 unsigned int 不应为负值。但是今天我在我的代码注意到这种情况:
I always use unsigned int for values that should never be negative. But today Inoticed this situation in my code:
void CreateRequestHeader( unsigned bitsAvailable, unsigned mandatoryDataSize,
unsigned optionalDataSize )
{
If ( bitsAvailable – mandatoryDataSize >= optionalDataSize ) {
// Optional data fits, so add it to the header.
}
// BUG! The above includes the optional part even if
// mandatoryDataSize > bitsAvailable.
}
我应该开始使用 int
推荐答案
我应该永远...的答案几乎肯定是 ',有很多因素决定你是否应该使用数据类型 - 一致性很重要。
The answer to "Should I always ..." is almost certainly 'no', there are a lot of factors that dictate whether you should use a datatype- consistency is important.
但是,这是一个非常主观的问题, up unsigneds:
But, this is a highly subjective question, it's really easy to mess up unsigneds:
for (unsigned int i = 10; i >= 0; i--);
会导致无限循环。
这就是为什么某些样式指南()阻止 unsigned
数据类型。
This is why some style guides (Google's included) discourage unsigned
data types.
我个人认为,我没有遇到过许多由无符号数据类型 - 我想说使用断言检查你的代码,并明智地使用它们(当你执行算术时更少)。
In my personal opinion, I haven't run into many bugs caused by these problems with unsigned data types - I'd say use assertions to check your code and use them judiciously (and less when you're performing arithmetic).
这篇关于你应该总是使用'int'C中的数字,即使它们是非负数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!