The importance of declaring a variable as unsigned

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

    There are two main things using unsigned gives you

    • it allows you to use the right shift >> operator safely on any value, as it can't be negative -- using a right shift on a negative value is undefined.

    • it gives you wrap-around mod 2^n arithmetic. With signed values, the effect of underflow/overflow is undefined. With unsigned values you get mod 2^n arithmetic, so 0U - 1U will always give you the largest possible unsigned value (which will always be 1 less than a power of 2).

提交回复
热议问题