【发布时间】:2023-03-20 11:01:01
【问题描述】:
$ gcc --version
gcc (Debian 4.9.2-10) 4.9.2
在下面的代码 sn-p 中,为什么表达式 100 < strlen(str) - 4 被评估为真?
#include <stdio.h>
#include <string.h>
int main(void)
{
char str[50];
scanf("%s", str);
printf("%d\n", strlen(str) - 4);
if(100 < (strlen(str) - 4))
printf("NOT POSSIBLE!\n");
return 0;
}
终端:
$ gcc so.c -o so
$ ./so
foo
-1
NOT POSSIBLE!
通过实验我发现:
-
if表达式对于任何 positive_int、negative_int 对的计算结果为 true,这样positive_int < negative_num(这是荒谬的),其中negative_int 是strlen函数调用的形式(参见 2。) - 如果我们将
strlen替换为硬编码的负整数,则if的计算结果与预期一样为false。strlen似乎有问题。
【问题讨论】:
-
因为 size_t 是无符号的。您可能会写
if (100 + 4 < strlen(str))以避免出现负数问题,从而获得正确的结果。 -
有关
size_t的更多信息,请参见this So post
标签: c if-statement strlen