strlen函数返回值为size_t类型,也就是unsigned int类型, 无符号数,永远大于零
看例子
1 #include <stdio.h> 2 #include <string.h> 3 int main() 4 { 5 char *buf_a = "abcdefg"; 6 char *buf_b = "aaaaaaaaaa"; 7 printf("buf_a = %d\n", strlen(buf_a)); 8 printf("buf_b = %d\n", strlen(buf_b)); 9 10 printf("buf_a - buf_b = %d\n", strlen(buf_a) - strlen(buf_b)); 11 int len = strlen(buf_a) - strlen(buf_b); 12 printf("%d\n", len); 13 if(len > 0) 14 { 15 printf("adf\n"); 16 } 17 if(strlen(buf_a) - strlen(buf_b) > 0) 18 { 19 printf("adfadf\n"); 20 } 21 return 0; 22 }
看结果
buf_a = 7
buf_b = 10
buf_a - buf_b = -3
-3
adfadf
千万不要像17行这么判断,原因你懂的,要将其转换为有符号的形式,如11行所示