将变量声明为无符号的重要性 [英] The importance of declaring a variable as unsigned

查看:141
本文介绍了将变量声明为无符号的重要性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果你知道它应该永远不是负的,那么将一个变量声明为unsigned是很重要的。

Is it important to declare a variable as unsigned if you know it should never be negative? Does it help prevent anything other than negative numbers being fed into a function that shouldn't have them?

推荐答案

声明语义上的变量是否有助于防止除了负数之外的任何东西被输入到不应该包含它们的函数中?非负值作为 unsigned 是一个好的风格和良好的编程实践。

Declaring variables for semantically non-negative values as unsigned is a good style and good programming practice.

但是,请记住,它不会阻止您犯错误。如果对于无符号整数分配负值是完全合法的,则根据无符号算术规则将值隐式转换为无符号形式。一些编译器可能会在这种情况下发出警告,其他人会安静地做。

However, keep in mind that it doesn't prevent you from making errors. If is perfectly legal to assign negative values to unsigned integers, with the value getting implicitly converted to unsigned form in accordance with the rules of unsigned arithmetic. Some compilers might issue warnings in such cases, others will do it quietly.

还值得注意的是,使用无符号整数需要知道一些专用的无符号技术。例如,关于这个问题经常提到的经典示例是向后迭代

It is also worth noting that working with unsigned integers requires knowing some dedicated unsigned techniques. For example, a "classic" example that is often mentioned with relation to this issue is backward iteration

for (int i = 99; i >= 0; --i) {
  /* whatever */
}

上面的循环看起来很自然,签名 i ,但它不能直接转换为无符号形式,意味着

The above cycle looks natural with signed i, but it cannot be directly converted to unsigned form, meaning that

for (unsigned i = 99; i >= 0; --i) {
  /* whatever */
}

不会真正做到它的意图(它实际上是一个无尽的循环)。这种情况下的正确技巧是

doesn't really do what it is intended to do (it is actually an endless cycle). The proper technique in this case is either

for (unsigned i = 100; i > 0; ) {
  --i;
  /* whatever */
}

for (unsigned i = 100; i-- > 0; ) {
  /* whatever */
}

这通常用作无符号类型的参数,即所谓的循环的上述无符号版本看起来不自然和不可读。在现实中,我们在这里讨论的问题是在封闭开放范围的左端附近工作的通用问题。这个问题在C和C ++中以许多不同的方式表现出来(例如使用使用迭代器在标准容器上使用向后迭代的滑动指针技术的向后迭代)。也就是说不管上面的无符号周期看起来多么不自然,即使你从不使用无符号整数类型,也没有办法完全避免它们。所以,最好是学习这些技术,并将它们包括在成熟的习语中。

This is often used as an argument against unsigned types, i.e. allegedly the above unsigned versions of the cycle look "unnatural" and "unreadable". In reality though the issue we are dealing here is the generic issue of working near the left end of a closed-open range. This issue manifests itself in many different ways in C and C++ (like backward iteration over an array using the "sliding pointer" technique of backward iteration over a standard container using an iterator). I.e. regardless of how inelegant the above unsigned cycles might look to you, there's no way to avoid them entirely, even if you never use unsigned integer types. So, it is better to learn these techniques and include them into your set of established idioms.

这篇关于将变量声明为无符号的重要性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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