Linear output C ++
When comparing, the const char*
result of "1"
u "0"
is undefined by the standard, whereas comparison 2 is std::string
defined and expected to exit in this case.
Quick example:
char* y = "0";
char* x = "1";
std::cout << (x<y) << endl;
//output 1 on my platform
and
char* x = "1";
char* y = "0";
std::cout << (x<y) << endl;
//output 0 on my platform
I am specifying "on my platform" because there is no standard rule (but it could be a compiler rule) where pointers are created or in what order they are created.
In my case, addresses are assigned in reverse order of announcement.
I bet that if you run:
cout << ("1" < "0") << endl;
and
cout << ("0" < "1") << endl;
you will get the same result (although this is not a rule). Please note that you must run them in different instances of the program. If you run them in the same instance, you might get different results, since the string literals are in the same place in memory.
source to share
The expression "1" <"0" compares the values of two pointers. One indicates the character sequence "1" and the other indicates the character sequence. Your compiler places character sequences in memory such that the address of the char sequence "1" is before "0".
With strings, however, the <(const string &, const string &) operator is called as expected.
source to share
Since you are comparing two pointers (strings "1"
and are "0"
represented as arrays char
, synonymous with (kinda) with a pointer to char). If you want to compare between the digits 0 and 1, you don't need quotes. Otherwise, you need a string comparison function that compares the contents of strings, not their addresses. It's best if you wrap them in std::string
and use a member function compare()
.
source to share