(转载)C语言中strlen()返回值类型为无符号数

(转载)http://blog.csdn.net/jubincn/article/details/7335726

参考:《C和指针》

strlen()的方法签名中的返回值类型为size_t,size_t实际上是一个无符号整型。因此,下面的代码就会有问题:

if( strlen(x) - strlen(y) >= 0 ) ... ;

if( strlen(x) - 10 >= 0) ... ;

这样,if语句永远都会执行,因为无符号数不存在负值。实际上,C中很多string相关函数返回值都是无符号数,在使用时要小心谨慎。


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char** argv)
{
    if (strlen("Z") - strlen("ZG") >= 0)
        printf("Exe1\n");

    if (strlen("ZhuHai") - 10 >= 0)
        printf("Exe2\n");

    return 0;
}

程序输出:

Exe1

Exe2

原文地址:https://www.cnblogs.com/Robotke1/p/3070357.html