Pitfalls in comparison between string.length() return value and negative value

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:

  1. Because negative values ​​are rarely used to compare with length() of string, this pitfall is not easy to find.
  2. In the future, you will develop a habit of int len = str.length()forcing the string length to be converted to int before use.

Guess you like

Origin blog.csdn.net/qingtu11/article/details/120035986