The importance of declaring a variable as unsigned

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

    Is it important to declare a variable as unsigned if you know it should never be negative?

    Certainly it is not important. Some people (Stroustrup and Scott Meyers, see "Unsigned vs signed - Is Bjarne mistaken?") reject the idea that a variable should be unsigned just because it represents an unsigned quantity. If the point of using unsigned would be to indicate that a variable can only store non-negative values, you need to somehow check that. Otherwise, all you get is

    • A type that silently hides errors because it doesn't let negative values to expose
    • Double of the positive range of the corresponding signed type
    • Defined overflow/bit-shift/etc semantics

    Certainly it doesn't prevent people from supplying negative values to your function, and the compiler won't be able to warn you about any such cases (think about a negative runtime based int-value being passed). Why not assert in the function instead?

    assert((idx >= 0) && "Index must be greater/equal than 0!");
    

    The unsigned type introduces many pitfalls too. You have to be careful when you use it in calculations that can temporary be less than zero (down counting loop, or something) and especially the automatic promotions that happen in the C and C++ languages among unsigned and signed values

    // assume idx is unsigned. What if idx is 0 !?
    if(idx - 1 > 3) /* do something */;
    

提交回复
热议问题