Comparing negative numbers in C -


i having problem program wrote. program going if statement whereas should not. have 2 variables:

size_t len = 5; int    tmp = -1; 

when :

if (tmp > len)     ft_putstr("this crazy"); 

i prints out "this crazy whereas -1 smaller 5 me ! ok, ok. looked on favorite website , saw this.

when trying:

printf("%zu", tmp)  

i see big positive number. ok ! might reason why program goes if condition above, how can make not go inside if condition ??? thanks

the problem here trying compare unsigned signed. means there's implicit conversion involved before actual conversion done. in case signed converted unsigned (which not 1 want - therefore many compilers have options display warning when done).

to more correct in sloppy way write:

 if( (int)tmp > (int)len ) 

however ignores fact size_t have values large int. strict 1 have handle range of int combined range of size_t larger available type. means have handle in 2 cases, use fact if tmp<0 tmp<len (mathematically, since len>=0). example mathematically tmp<len written tmp<0 || tmp<len. , opposite tmp>=0 && tmp >= len. should therefore write:

 if( tmp >= 0 && tmp > len ) 

note conversion not problem, tmp after first check converted unsigned without change of value, different ranges of int , size_t not problem either smaller converted wider range before comparison.

the problem left if have enabled warnings signed-unsigned comparison (to detect these kind of mistakes) still warn. take care of need explicitely type cast it, know conversion unsigned doesn't change tmp once checked tmp>=0. avoid warnings write:

if( tmp >= 0 && (unsigned)tmp > len) ) 

the (unsigned) because tmp int, need respect type when converting unsigned if tmp of type.


Comments