The importance of declaring a variable as unsigned

前端 未结 14 3261
臣服心动
臣服心动 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条回答
  •  无人及你
    2021-02-20 06:32

    This has value for the same reason that "const correctness" has value. If you know that a particular value shouldn't change, declare it const and let the compiler help you. If you know a variable should always be non-negative, then declare it as unsigned and the compiler will help you catch inconsistencies.

    (That, and you can express numbers twice as big if you use unsigned int rather than int in this context.)

提交回复
热议问题