1

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?

router
  • 582
  • 5
  • 16
  • 4
    You are not comparing strings, you are comparing pointers. `"100" < "10"` could be true or false depending where the string literals are located in memory. Try `str < "10"` – john Nov 30 '22 at 18:48
  • Thank you @john. Got it. Is there any possible explanation for why I always get true for "100" < "10" for the above code on multiple machines, consistently? – router Dec 01 '22 at 03:29
  • 1
    Presumably that's dependent on the compiler you are using. I ran your code on my compiler and got `1 0` (and a compiler warning message). – john Dec 01 '22 at 06:59

1 Answers1

1

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.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • 1
    I think the result is only [unspecified, not undefined](https://stackoverflow.com/questions/31774683/is-pointer-comparison-undefined-or-unspecified-behavior-in-c). Important because while you can't predict whether `("100" < "10")` will be `true` or `false`, it will be one of those two and not "the behavior of the entire enclosing program is undefined". – Nathan Pierson Nov 30 '22 at 18:53
  • @NathanPierson According to the C Standard the behavior is undefined. In the C++ Standard there is written "Otherwise, neither pointer compares greater than the other.". So it is also undefined behavior. – Vlad from Moscow Nov 30 '22 at 19:01
  • @NathanPierson It is interesting written in the C++ 20 Standard (7.6.9 Relational operators, p.4) "— Otherwise, neither pointer is required to compare greater than the other. – Vlad from Moscow Nov 30 '22 at 19:16