我的编译器:Dev C++ 5.3.0.3 TDM-GCC 4.6.1 64 位 我的操作系统:Windows 7,64 位
我的 C 代码:
# 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;
}
我的问题:为什么打印“haha”?!(0>-1?!!!) 感谢您的帮助!
最佳答案
strlen
返回一个 unsigned 值,比较 i < strlen(text) - 1
对无符号整数执行,其中0
确实不比另一个大。
在处理无符号类型时,如果只使用 +
会容易得多。 :
if (i + 1 <= strlen(text))
或者更好:
if (i < strlen(text))
理解内置类型和运算符的算术提升和转换可能有点棘手,但可能值得一读。肯定有一些意想不到的情况。一个好的编译器可以在你 comparing signed with unsigned types
时警告你.
(如果您好奇为什么同时具有有符号和无符号类型的表达式都被提升为无符号,您可能会注意到从有符号到无符号的转换是绝对明确定义的(通过模运算),而从无符号的转换to signed 是实现定义的。我想这意味着提升规则意味着算术运算和比较的行为是明确定义的,而不仅仅是实现定义的。)
关于c - 短 C 代码 : Confused strlen() function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14674825/