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
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 int
s, after all, odds are you aren't have a window wide enough to need it to be unsigned
.