How to compare signed and unsigned (and avoid problems)

I recently heard that matching / unsigned comparisons can be complicated in C. for example, signed / unsigned comparisons , as well as some other issues.

My question is that if we need to compare a single type with unsigned (for example, include =,>, <operators) , what strategies exist to avoid the problems that result from such a comparison ?

Or should we make sure that we always compare only intwith intand unsignedwith unsigned?

PS. It would also be good to know when such comparisons are dangerous?

+4
source share
1 answer

It’s best to make sure your types match in advance. But if you cannot:

If you know that it intwill definitely not have a negative value at this point, draw it on unsigned.

If you know that the value unsignedwill be less than INT_MAX, translate it into int.

If neither of them is held, translate both values ​​into a type that is large enough to hold all possible values ​​that need to be processed. Another possibility (when there is no sufficiently large type) is to use two comparisons: first compare intwith 0, and if it is non-negative, add it to unsignedand compare with the value unsigned.

, int unsigned, , , .

int unsigned , int . - , unsigned, .

+2

Source: https://habr.com/ru/post/1534898/


All Articles