I have a piece of code where I see a warning saying
I am doing a comparison between signed and unsigned number .
Something like int <= CONSTANT/sizeof(expression)
What is the best way to correct this? I believe to take the modulus of signed number and then do the comparison, right? I mean I get the unsigned number after division by sizeof operator on an expression. So the other way could be to make this rhs signed
If so is there a function in c that would let me do this? I did a quick search and they say % for modulo which obviously is not what I am looking for.
This is the actual warning
warning: comparison between signed and unsigned integer expressions
and this is the actual line of code
functionA( ……, int num, …..) {
assert( num <= MAX_SIZE/sizeof(int));//where MAX_SIZE is #define
MAX_SIZE 1000}
Just cast one side to the other signedness. You have to make sure that the signed number is not negative if you cast that to unsigned – otherwise a comparison of
-1 < 100will not have the desired outcome, since(unsigned)(-1) == UINT_MAX-, or that the unsigned number doesn’t overflow if you cast that to signed. In those cases, add an additional condition to treat them.For the above particular case, I would use
if
nummight be negative andif
numis guaranteed to be nonnegative.