Home > OS >  string relational operator comparison vs string::compare() in cpp
string relational operator comparison vs string::compare() in cpp

Time:12-02

In short I am getting different output for string comparison using string::compare() vs relational operator '<' on std::string class objects.

string str = "100";
cout << str.compare("10")<<endl; //prints 1
cout << ("100" < "10") <<endl; //prints 1

Here's the demo url

lexicographically "100" is greater than "10" and hence ("100" <"10") must print 0 since it's false but the output 1 i.e true is not expected. The str.compare() function returns > 0 which is expected validating "100" > "10". Why is this happening?

CodePudding user response:

In this statement

cout << ("100" < "10") <<endl;

you are comparing two pointers of the type const char * to which the used string literals are implicitly converted. The result of such a comparison is undefined (At least in the C Standard there is explicitly stated that such operation is undefined).

In fact the above statement is equivalent to

cout << ( &"100"[0] < &"10"[0] ) <<endl;

If you want to compare strings the you need to write at least like

cout << (std::string( "100" ) < "10") <<endl;

In this case the output will be

0

Pay attention to that according to the C 20 (7.6.9 Relational operators)

  1. ...The comparison is deprecated if both operands were of array type prior to these conversions

And the both string literals prior to comparison have array types.

  • Related