The importance of declaring a variable as unsigned

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

    The other answers are good, but sometimes it can lead to confusion. Which is I believe why some languages have opted to not have unsigned integer types.

    For example, suppose you have a structure that looks like this to represent a screen object:

    struct T {
        int x;
        int y;
        unsigned int width;
        unsigned int height;
    };
    

    The idea being that it is impossible to have a negative width. Well what data type do you use to store the right edge of the rectangle?

    int right = r.x + r.width; // causes a warning on some compilers with certain flags
    

    and certainly it still doesn't protect you from any integer overflows. So in this scenario, even though width and height cannot be conceptually be negative, there is no real gain in making them unsigned except for requiring some casts to get rid of warnings regarding mixing signed and unsigned types. In the end, at least for cases like this it is better to just make them all ints, after all, odds are you aren't have a window wide enough to need it to be unsigned.

提交回复
热议问题