Rizescu
Rizescu

Reputation: 121

C++ Char - Relational Operators

I have a little problem working on with char in C++ as I have tried comparing 2 texts in an if and there is what I've got:

Input:

if ( "bac" < "ab" ) cout<<"1";
if ( "ab" > "bac" ) cout<<"1";

Output :

11

I don't really understand why it is printing "11", but moreover if I erase the first 'if' it will no longer print anything on the screen. Could you please explain why it has such a behaviour on these IFs?

Upvotes: 1

Views: 756

Answers (2)

lakeweb
lakeweb

Reputation: 1939

`if("abc" < "bcd" );

This is equivalent to:

char* a= "abc";
char* b ="bcd";
if( a < b );

a and b are pointers, addresses in memory. So no matter what are in the two strings, they are in different places in memory. That means no matter what the content of the two strings, a will never be equal to b.

When you "abc" you get the memory location of that string. So that is what is meant by, "You are comparing pointers."; C++ is not like other languages where the machine is abstracted away. You are working with the real one's and zero's that the machine uses. And everything lives somewhere in memory.

strcmp is a function that take two pointers then compares the values in the memory location that those pointers refer to.

if( ! strcmp(a,b) )
   ;//then the two strings are the same

Upvotes: 1

Sid S
Sid S

Reputation: 6125

You are comparing pointers, not characters.

If you're using a modern compiler you can do it like this instead:

if ("bac"s < "ab"s) cout << "1";
if ("ab"s > "bac"s) cout << "1";

The s suffix tells the compiler that the string literals are of type std::string.


If your compiler doesn't support that, you can do it the old fashioned way:

if (string("bac") < string("ab")) cout << "1";
if (string("ab") > string("bac")) cout << "1";

Or the ancient C-style way:

if (strcmp("bac, "ab") < 0) cout << "1";
if (strcmp("ab, "bac") > 0) cout << "1";

Upvotes: 0

Related Questions