3

I was trying to learn about "<" operator on c++ strings and tried some test cases. I realized the two codes which I thought should behave the same was giving different results. Below are the codes, what is the reason for this?

  string s="test";
  string k="tes";
  cout<<(s<k)<<endl; //returns false so it prints 0
  cout<<("test"<"tes")<<endl; // returns true so it prints 1
OgiciBumKacar
  • 311
  • 1
  • 3
  • 10

2 Answers2

4

(s < k) compares the values of the strings as you would expect.

("test" < "tes") compares the pointers to the beginning of the string literals as the compiler decides to arrange them in memory. Therefore, this comparison may return 0 or 1 depending on the compiler and settings in use, and both results are correct. The comparison is effectively meaningless.

The "C way" to compare these string literals would be strcmp("test", "tes").

cdhowie
  • 158,093
  • 24
  • 286
  • 300
0

s and k are string objects for which a comparison operator has been defined and performs what you expect.

"test" and "tes" are pointers to char that hold the address of the locations where these characters are stored. Thus the comparison is on the addresses.