The hidden pitfalls of string.length() return value
The return value of string.length() is size_t, which is an unsigned integral type. When we use string.length() to compare the size with int, the int value will be implicitly converted to unsigned integral! !
An error occurs when comparing a negative int to string.length()
#include <iostream>
#include <string>
#include <typeinfo>
#include <cxxabi.h>
using namespace std;
int main ()
{
int f = -1;
int n = 2;
string str ("Test string");
if(f < str.length()) {
//f被转换成unsigned 类型,导致比较结果和我们的认知相反
cout<<"f < str.length() is true"<<endl;
}
else {
cout<<"f < str.length() is false"<<endl;
}
if(n < str.length()) {
cout<<"n < str.length() is true"<<endl;
}
else {
cout<<"n < str.length() is false"<<endl;
}
cout <<"string length type:"<< abi::__cxa_demangle(typeid(str.length()).name(), nullptr, nullptr, nullptr) << endl;
return 0;
}
Output result:
f < str.length() is false
n < str.length() is true
str.length() > f is false
string length type:unsigned long
Summarize:
- Because negative values are rarely used to compare with length() of string, this pitfall is not easy to find.
- In the future, you will develop a habit of
int len = str.length()
forcing the string length to be converted to int before use.