The Microsoft C compiler warns when you try to compare two variables, and one is signed, and the other is unsigned. For example:
int a;
unsigned b;
if ( a < b ) { // warning C4018: '<' : signed/unsigned mismatch
}
Has this warning, in the history of the world, ever caught a real bug? Why's it there, anyway?
@gimel The explanation about shoot the entire leg of found behind your link is really good for this problem.
This is actually always true when you convert between different types and you don't check for those values that could hurt you.
/Johan
Update: The correct way to convert from uint to int is to check the values against limits.h, or something like that. (But I seldom do that my self, even thou I know I should... :-)
I've been writing code longer than I'd care to admit. From personal experience ignoring seemingly pedantic compiler warnings can sometimes yield very unpleasent results.
If they annoy you and you accept/understand the situation then set a cast and move on.
Eventually these things move from an overlooked nuance into a conscious decision when designing new code. The result leaves less room for mickmouse corner cases to ruin your or your customers day and overall better quality software.
I think its best to convert your UNsigned number into a signed number (before the comparison). Rather than the other way around.
Never ignore compiler warnings.
You should change
a
andb
to both use signed types, or both use unsigned types. But that may not be practical (e.g. it maybe outside your control).The warning is there to catch comparisons between a signed integer with a negative value and an unsigned integer -- if the magnitudes of both numbers are small, the former will (incorrectly) be deemed larger than the latter.
Just one of the many ways in which C allows you to shoot yourself in the foot - you'd better know what you are doing. The C quote is attributed to Bjarne Stroustrup, creator of C++.