在 VS2013 中处理这一小段代码,但由于某种原因它没有打印。似乎 -1>strlen(str)
任何人都知道我做错了什么
char *str="abcd";
if(-1<strlen(str))
printf("The size of the string is %d", strlen(str));
return 0;
任何人都知道我做错了什么
strlen()
返回一个size_t
,这是一个无符号整数类型。-1
解释为无符号整数是一个很大的值,因此它最终大于字符串的长度。您可以使用-Wsign-compare
标记在gcc
以及其他一些编译器会在您尝试比较有符号值和无符号值时发出警告。
此外,将字符串的长度与-1
。长度永远不能为负;它是always将0
或更大。所以你可能想重写你的代码来测试0
,或者以其他方式正确实现您要测试的任何条件。
if(-1<strlen(str))
printf("The size of the string is %d", strlen(str));
In this code, you might reasonably expect the test to always succeed and the printf()
to execute, since the length is always 0
or more. But you're finding that the test actually fails and the printf()
never happens because -1
is promoted to an unsigned so that it can be compared to a size_t
. The easy solution is to remove the condition altogether: you know the test will always succeed, so there's no need for it. Just remove the if
*:
printf("The size of the string is %zu", strlen(str));
*Also, change the print format specifier from %d
to %zu
since, as Matt McNabb pointed out in a comment, you're trying to print a size_t
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)