何时在有符号值上使用无符号值? [英] When to use unsigned values over signed ones?

查看:24
本文介绍了何时在有符号值上使用无符号值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么时候在有符号变量上使用无符号变量合适?在 for 循环中怎么样?

When is it appropriate to use an unsigned variable over a signed one? What about in a for loop?

我听到了很多关于这个的意见,我想看看是否有任何类似共识的东西.

I hear a lot of opinions about this and I wanted to see if there was anything resembling a consensus.

for (unsigned int i = 0; i < someThing.length(); i++) {  
    SomeThing var = someThing.at(i);  
    // You get the idea.  
}

我知道 Java 没有无符号值,这肯定是对 Sun Microsystems<的明智决定/a>' 部分.

I know Java doesn't have unsigned values, and that must have been a concious decision on Sun Microsystems' part.

推荐答案

我很高兴找到 关于这个主题的很好的对话,因为我之前并没有真正考虑过它.

I was glad to find a good conversation on this subject, as I hadn't really given it much thought before.

总而言之,如果您要对变量进行算术运算(例如在典型的 for 循环情况下),则签名是一个不错的一般选择 - 即使您已经确定所有数字都是正数.

In summary, signed is a good general choice - even when you're dead sure all the numbers are positive - if you're going to do arithmetic on the variable (like in a typical for loop case).

未签名在以下情况下开始变得更有意义:

unsigned starts to make more sense when:

  • 您将要做按位操作,例如掩码,或者
  • 渴望利用符号位获得额外的正范围.
  • You're going to do bitwise things like masks, or
  • You're desperate to to take advantage of the sign bit for that extra positive range .

就我个人而言,我喜欢签名,因为我不相信自己会保持一致并避免混合使用这两种类型(就像文章中警告的那样).

Personally, I like signed because I don't trust myself to stay consistent and avoid mixing the two types (like the article warns against).

这篇关于何时在有符号值上使用无符号值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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