Reputation: 31549
The following code, comes from the article C++ quirks, part 198276
include <iostream>
#include <string>
using namespace std;
int main()
{
std::string a = "\x7f";
std::string b = "\x80";
cout << (a < b) << endl;
cout << (a[0] < b[0]) << endl;
return 0;
}
Surprisingly the output is
1
0
Shouldn't string comparison be lexicographical ? If yes how is the output explained?
Upvotes: 3
Views: 655
Reputation: 81976
So I'm just going to quote directly from your link:
It turns out that this behavior is required by the standard, in section 21.2.3.1 [char.traits.specializations.char]: “The two-argument members eq and lt shall be defined identically to the built-in operators == and < for type unsigned char .”
So:
(a < b)
is required to use unsigned char
comparisons.(a[0] < b[0])
is required to use char
comparisons, which may or may not be signed.Upvotes: 2
Reputation: 409356
There is nothing in the C++ specification to say if char
is signed
or unsigned
, it's up to the compiler. For your compiler it seems that char
defaults to signed char
which is why the second comparison returns false
.
Upvotes: 3