c - 为什么 (positive_integer < negative_integer) 被评估为 true?

标签 c if-statement strlen

$ 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!  

通过一些实验我发现:

  1. if对于满足 positive_int < negative_num 的任何 positive_int、negative_int 对,表达式的计算结果为真(这很荒谬)negative_int 的形式是 strlen函数调用(见 2.)
  2. 如果我们替换 strlen然后用硬编码的负整数 if评估为 false正如预期的那样。看起来 strlen 有问题.

最佳答案

由于 strlen 的类型为 size_t4 被转换为(无符号)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 the sizeof 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/

相关文章:

C 编程 : Finding the Longest Word from A Dictionary with Given Characters

c - C 中指针的错误管理

c - 使用C语言注入(inject)dll

python - 如何检查字符串是否包含 Python 列表中的元素

excel - 无所不在: Application defined or object defined error

javascript检测div类的存在,如果为真,则更改不同div的innerHTML

c - GCC 中 strlen() 的实现在哪里?

c - 如何在 C 中的 PQexecParams() 中使用多个变量

c - 为什么strlen()替换一个字符串?

c - 为什么 strlen 在没有 '\0' 的情况下工作正常?