The importance of declaring a variable as unsigned

前端 未结 14 3245
臣服心动
臣服心动 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:41

    It won't prevent negative numbers from being fed into a function; instead it will interpret them as large positive numbers. This may be moderately useful if you know an upper bound for error checking, but you need to do the error checking yourself. Some compilers will issue warnings, but if you're using unsigned types a lot there may be too many warnings to deal with easily. These warnings can be covered up with casts, but that's worse than sticking to signed types only.

    I wouldn't use an unsigned type if I knew the variable shouldn't be negative, but rather if it couldn't be. size_t is an unsigned type, for example, since a data type simply can't have negative size. If a value could conceivably be negative but shouldn't be, it's easier to express that by having it as a signed type and using something like i < 0 or i >= 0 (these conditions come out as false and true respectively if i is an unsigned type, regardless of its value).

    If you're concerned about strict Standard conformance, it may be useful to know that overflows in unsigned arithmetic are fully defined, while in signed arithmetic they're undefined behavior.

提交回复
热议问题