Problem in comparing strings without assigning to variable

Viewed 72
int i = ("aac" > "aab");
cout << i;

The above code does not give me the output as 1 (as it should be). But when I assign "aac" and "aab" to two separate string variables and use the variables instead of using strings directly (code attached below), I get the desired output.

Could anyone help me please?

string s1 = "aac";
string s2 = "aab";
int i = (s1 > s2);
cout << i;
2 Answers

Literal constants like "aac" aren't std::string objects; rather, they are just data in (read-only) memory that evaluate, in most 'access' cases, to the address of their first element (i.e. a char* pointer); so, a comparison between them will be a comparison between those addresses — something you are unlikely to be able to control or predict.

To get an inline comparison, in your case, you can use inline std::string constructors (sometimes knows as "wrappers"), like this:

    int i=(string("aac")>string("aab"));

Or, using the more 'modern' "curly-brace" initializer syntax:

    int i = (string{ "aac" } > string{ "aab" });

For more brevity, you can make use of the fact that std::string has versions of the > (and similar) operators that take a string literal as one of the arguments; thus, you need only 'wrap' one of the literals, and could reduce the above code to something like:

    int i = (string{ "aac" } > "aab");

If you use C-style char * / char [] strings, you need to use strcmp like:

int i = strcmp("aac", "aab");

Otherwise, you are just comparing addresses of the first elements of both of strings.

Related