My compiler: Dev C++ 5.3.0.3 TDM-GCC 4.6.1 64-bit
My OS: Windows 7, 64bits
My C Code:
# include "stdio.h"
# include "string.h"
# define MAX (501)
int main() {
char
text[MAX]="";
int i;
i=0;
printf("%d\n",strlen(text)); /* 0 */
printf("%d\n",(strlen(text)-1)); /* -1 */
if ( i<= (strlen(text)-1) ) printf("haha"); /* haha */
return 0;
}
My question: Why “haha” is printed?! ( 0>-1 ?!!!)
Thanks for your help!
strlenreturns an unsigned value, and the comparisoni < strlen(text) - 1is performed for unsigned integers, in which0is indeed no larger than the other.When dealing with unsigned types, it is far easier to reason about if you only use
+:Or even better:
It can be a bit tricky to understand the arithmetic promotions and conversions for the built-in types and operators, and it might be worth reading up on those. There are certainly some unexpected situations. A good compiler can be made to warn you when you are
comparing signed with unsigned types.(If you’re curious why in an expression with both signed and unsigned types both get promoted to unsigned, you may note that the conversion from signed to unsigned is absolutely well defined (via modular arithmetic), while the conversion from unsigned to signed is implementation-defined. I suppose that means that the promotion rules mean that the behaviour of arithmetic operations and comparisons is well-defined, rather than just implementation-defined.)