如果你总是用'诠释'在C号,即使他们都是非负? [英] Should you always use 'int' for numbers in C, even if they are non-negative?

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

问题描述

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

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

我应该开始使用的内部而不是 unsigned int类型作为数字,即使他们
不能为负?


解决方案

  

我就应该总是...


这个问题的答案我就应该总是......几乎可以肯定是'不',也有很多的因素决定你是否应该使用datatype-的一致性是非常重要的。

不过,这是一个非常主观的问题,它真的很容易搞乱unsigneds:

 为(unsigned int类型我= 10; I> = 0;我 - );

在一个无限循环的结果。

这就是为什么一些风格指南(谷歌的包括)劝阻无符号的数据类型。

在我个人的看法,我还没有碰到许多错误造成这些问题的无符号的数据类型 - 我会说使用断言检查你的code和明智地使用它们(当你正在执行少算术)。

I always use unsigned int for values that should never be negative. But today I noticed 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.
}

Should I start using int instead of unsigned int for numbers, even if they can't be negative?

解决方案

Should I always ...

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号,即使他们都是非负?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆