本文介绍了如果你总是用'诠释'在C号,即使他们都是非负?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直使用 unsigned int类型作为价值的不应该是否定的。但今天我
在我的code注意到了这种情况:

 无效CreateRequestHeader(无符号bitsAvailable,无符号​​mandatoryDataSize,
    无符号optionalDataSize)
{
    如果(bitsAvailable - mandatoryDataSize> = optionalDataSize){
        //可选数据符合,所以它添加到报头。
    }    // BUG!以上内容包括可选的部分,即使
    // mandatoryDataSize> bitsAvailable。
}

我应该开始使用的内部而不是 unsigned 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.

But, this is a highly subjective question, it's really easy to mess up unsigneds:

for (unsigned int i = 10; i >= 0; i--);

results in an infinite loop.

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).

这篇关于如果你总是用'诠释'在C号,即使他们都是非负?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 00:11