Apologies if this seems like a silly q, but why do the statements
cout << ("0" < "1")
cout << ("1" < "0") both return true?
:confused:
Printable View
Apologies if this seems like a silly q, but why do the statements
cout << ("0" < "1")
cout << ("1" < "0") both return true?
:confused:
Because you're comparing pointers (to strings) rather than strings.
Try with
Code:#include <string>
std::string zero = "0";
std::string one = "1";
cout << (zero < one);
similarily
Code:cout << (*"0" < *"1");
cout << (*"1" < *"0");
Ah, but what about (*"10" < *"11") ?Quote:
Originally Posted by MadCow257
Thankyou all for such quick replies! :)
I'm still unclear on exactly how my example was working though.. I'm guessing that I was comparing pointers to both strings and so whatever I have on the left of the operator, the value of that pointer will always be less than that of the right pointer because of the order im putting them in memory? is this right or just rubbish? :)
You are correct in that you've compared the memory addresses of the strings.Quote:
Originally Posted by rayman
Whether the left or right string gets put in memory at a lower-valued memory location depends on the compiler and its behavior is generally unpredictable.
Whenever a string literal is encounted in a program(i.e. something between double quotes), the program slaps a '\0' character on the end of the string literal, stores it in memory somewhere, and returns the address. So, the line:Quote:
I'm still unclear on exactly how my example was working though.
cout << ("0" < "1")
becomes:
cout<<(address of str1 < address of str2);
I'm kind of confused too
What's different with this
(*"10" < *"11")
and this
(*"0" < *"1")
*"10";
<==>
const char* const c = "10";
*c;
<==>
const char* const c = "10";
c[0];
<==>
'1'
not 10
I think you mean '1', not 1.
Magos??? How about this:Quote:
I'm kind of confused too
What's different with this
(*"10" < *"11")
and this
(*"0" < *"1")
Code:const char* ptr1 = "123456789";
const char* ptr2 = "1";
cout<<*ptr1<<endl; //'1'
cout<<*ptr2<<endl; //'1'
If that really happens with your compiler then I think it has to do that your compiler doesn't optimize string literals. It propably creates a char array for every literal in you program and doesn't check for duplicates.Quote:
Originally Posted by rayman
g++ does
my outputCode:# include <iostream>
# include <iomanip>
using namespace std;
int main() {
cout << boolalpha;
cout << "1 < 0 = " << ( "1" < "0" ) << endl;
cout << "0 < 1 = " << ( "0" < "1" ) << endl;
return 0;
}
As far as I know this is implementation defined behavour.Code:1 < 0 = true
0 < 1 = false
Kurt
It is. Compilers are free to store string literals anywhere, in any order.Quote:
As far as I know this is implementation defined behavour.
If you want to compare string literals properly, use strcmp() or strings:
Code:if(strcmp("0", "1") < 0) { /* 0 is < 1 */ }
string one = "1", two = "2";
if(one < two) { /* 1 is < 2 */ }
if(string("11") < string("7")) { /* 11 is < 7 */ }