简体   繁体   中英

C++ line output

cout << boolalpha ("1" < "0") << endl;

I was compiling this recently as a spin off from some course work I was doing. Why does this produce true when I execute it?

cout << boolalpha (string("1") < string("0")) << endl;

does the comparison as expected.

It's comparing const char* , the result of "1" and "0" is undefined by the standard, whereas the comparison of 2 std::string s is defined and your output in that case is expected.

Quick case in point:

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'm specifying "on my platform" because there's no standard rule (but it can be a compiler rule) to where the pointers are created or in which order they are created.

In my case, the addresses are assigned in reverse order of declaration.

I'm willing to bet that if you run:

cout << ("1" < "0") << endl;

and

cout << ("0" < "1") << endl;

you'd get the same output (although it's not a rule). Note that you should run them in different instances of the program. If you run them in the same instance, you might get different results, as string literals reside in a single place in memory.

Expression "1" < "0" compares values of two pointers. One points to character sequence "1" and the other points to character sequence. Your compiler placed character sequences in memory in such a way that address of char sequence "1" is before that of "0".

With strings, however, operator<(const string&, const string&) is called, as expected.

Because you are comparing two pointers (the strings "1" and "0" are represented as arrays of char , synonymous (kinda) with pointer to char). If you want the comparison between the numbers 0 and 1, you don't need the quotes. Otherwise you need a string comparison function that compares the content of the strings, not their addresses. Best if you wrap them in an std::string and use the compare() member function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM