Past paper question from 2007:
Source University of Cape Town - CSC2001F - 2007

Which of the two statements shown below will provide an lexicographical (alphabetic) string comparsion?
why?

char *mesg1 = "Hello", *mesg2 = "world";
string s1 = "Hello", s2 = "world";
if (s1 != s2) {...} // statement 1
if (mesg1 != mesg2 ) {...} // statement 2

I thought both of these would provide alphabetic string comparison... But I guess I'm wrong.. What would be the correct answer

Not true. In the second if statement you are effectively performing a comparison of the pointer, not the content.

The string comparison will, on the other hand, give you a comparison of the content. You could use std::lexicographical_compare to compare a char array though.

okay so if you're performing a comparison of the pointer then why does

char *a = "Hello";
char *b = "Hello";

if(a == b)
{
cout << "EQUAL";
}

and the output prints

EQUAL

also writing:

cout << a

prints out

Hello

Because the compiler does some optimisation for you. Because you've defined two strings and you haven't changed them, the compiler assumes they are constant and assigns the same pointer address. This saves memory as instead of 2 * 6 bytes it's only 1*6 bytes.

Your if statement then effectively sees if(a == a)

Your result is compiler (option) specific.
You're probably compiling with "Optimize for speed (O2)", if you remove this option you will probably not see EQUAL being printed (at least not with my compiler).
So try to compile with different options, and print the addresses of a and b ;).

In any case, it really makes sense that you are comparing pointers, after all.. a and b _are_ pointers, and you are comparing them... there is no reason for the compiler to care about what a and b point to in the comparison.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.