The importance of declaring a variable as unsigned

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

    It does two things:

    1) It gives you double the range for your unsigned values values. When "signed" the highest bit is used as the sign bit (1 means negative, 0 for positive), when "unsigned" you can use that bit for data. E.g., a char type goes from -128 to 127, an unsigned char goes form 0 to 255

    2) It affects how the >> operator acts, specifically when right shifting negative values.

提交回复
热议问题