$ gcc --version
gcc (Debian 4.9.2-10) 4.9.2
在下面的代码片段中,为什么表达式是 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_num
的任何 positive_int、negative_int 对,表达式的计算结果为真(这很荒谬)negative_int 的形式是strlen
函数调用(见 2.)- 如果我们替换
strlen
然后用硬编码的负整数if
评估为false
正如预期的那样。看起来strlen
有问题.
最佳答案
由于 strlen
的类型为 size_t
,4
被转换为(无符号)size_t
,然后从 strlen
的返回值,然后将结果与100
进行比较。
6.3.1.8 Usual arithmetic conversions
....
Otherwise, if both operands have signed integer types or both have unsigned integer types, the operand with the type of lesser integer conversion rank is converted to the type of the operand with greater rank.Otherwise, if the operand that has unsigned integer type has rank greater or equal to the rank of the type of the other operand, then the operand with signed integer type is converted to the type of the operand with unsigned integer type.
7.24.6.3 The strlen function
....
size_t strlen(const char *s);
7.19 Common definitions
....
size_t
which is the unsigned integer type of the result of thesizeof
operator;
附言顺便说一句,即使在更简单的情况下,如
if (strlen("") < -1)
printf("OK\n");
else
printf("NOK\n");
,输出将是 OK
。
关于c - 为什么 (positive_integer < negative_integer) 被评估为 true?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34480975/