user3050705
user3050705

Reputation: 487

Comparison of letters and strings in C++

Why this code

if ("j" > "J")

return false, but this:

string a = "j";
string b = "J";

if (a > b)

return true? Which is the correct answer and how can i fix it?

Upvotes: 4

Views: 443

Answers (4)

RockLegend
RockLegend

Reputation: 507

That is happenig because "j" and "J" are const char []. For exampe "j" is array of chars that c[0]='j' and c[1]='\0'. In C and C++ you can't compare two arrays. it is better to use

strcmp("j","J");

witch is in

When you type

string a="j"

you run constructor in class string. But in class string you have overloaded operator< to compare two strings.

Upvotes: 2

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

This is because "j" and "J" are string literals, which are compared as const char pointers. The result of the comparison is therefore arbitrary, because the placement of literals in memory is implementation defined.

On the other hand, when you make std::string objects from these string literals, the < operator (along with other comparison operators) is routed to an override provided by the std::string class. This override does a lexicographic comparison of the strings, as opposed to comparing pointer values, so the results of comparison look correct.

Upvotes: 2

Yantao Xie
Yantao Xie

Reputation: 12896

You can try

if ("J" < "j")

and may be get a different result.

In fact "J" and "j" are constant C strings and may be placed on .data or .text sections which is determined by the output binary file format. So when you compare them, you are comparing their address in the memory.

But std::string is a C++ class which overloads the > operator, so it's not address/pointer comparing but content comparing.

Upvotes: 0

VladimirM
VladimirM

Reputation: 817

You can use single quotes to compare symbols: if ('j' > 'J')

Upvotes: 2

Related Questions