C语言的"bug" 隐式类型转换
原始code
#include<stdio.h>
#include<string.h>
int main()
{
const char * test_str="C trap";
printf("pre-view the length of test_str is %u.\n",strlen(test_str));
if(-1 < strlen(test_str))
printf("length of test_str is %u.\n",strlen(test_str));
else
printf("error.\n");
return 0;
}
希望的输出
pre-view the length of test_str is 6
length of test_str is 6
实际输出
为什么
首先我们来看一下 strlen 和 sizeof 的返回值,
根据ISO C11 7.24.6.3描述
strlen的返回值为size_t
根据ISO C11 7.19
size_t is the unsigned integer(是一个无符号整型)
sizeof 同理
根据C语言隐式类型转换的原理,如果是int型与uint型进行比较(其它类型同理),则会将int型数据转换为uint型,则-1变成了 2^32-1 = 4294967295 ,所以原始code中的 if condition 几乎永远不会满足。
正确code
#include<stdio.h>
#include<string.h>
int main()
{
const char * test_str="C trap";
printf("pre-view the length of test_str is %u.\n",strlen(test_str));
//if(0 <= strlen(test_str)) or
if(-1 < (int)strlen(test_str))
printf("length of test_str is %u.\n",strlen(test_str));
else
printf("error.\n");
return 0;
}