The importance of declaring a variable as unsigned

前端 未结 14 3303
臣服心动
臣服心动 2021-02-20 05:55

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 th

14条回答
  •  猫巷女王i
    2021-02-20 06:22

    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 */
    }
    

    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 */
    }
    

    or

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

    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.

提交回复
热议问题