strlen()函数细节问题

来源:互联网 发布:911事件知乎 编辑:程序博客网 时间:2024/05/22 21:29

strlen()函数的结果值为unsigned int 类型,在进行int和unsigned int比较时,会进行数值转换,因此这种细节问题应该注意。
一般在使用strlen函数时,多数情况下是用int 定义的变量来储存strlen的值。

可以运行下面两个程序试一试:

1、

#include <iostream>#include <stdio.h>#include <string.h>#include <algorithm>using namespace std;int main(){    unsigned int a = -1;    int b = 0;    if(a > b)cout<<"YES"<<endl;    else cout<<"NO"<<endl;    return 0;}

会发现输出结果为yes。

2、

#include <iostream>#include <stdio.h>#include <string.h>#include <algorithm>using namespace std;int main(){    unsigned int a = 0;    int i = 0;    for(; i >= a; i--)        cout<<"1"<<endl;    return 0;}

会发现程序一直输出1,不能结束循环。

原创粉丝点击