String COmpare

Jul 24, 2013 at 2:43am

The Statement if ( "ben" > "BEN" ) ... result is FALSE

will not give the same result with

string name1 = "ben";
string name2 = "BEN";

if ( name1 > nname2 ).... result is TRUE


Why are they giving different results ?



Jul 24, 2013 at 2:48am
"ben" and "BEN" are C strings, name1 and name2 are C++ strings. Only C++ strings have meaningful comparison operators.
Jul 24, 2013 at 9:51am
( "ben" > "BEN" ), is a pointer comparison, where as

( name1 > nname2 ) is string comparison, and in C++ you can overload the operators.
Jul 24, 2013 at 10:28am
String literals have type const char [] in C++ (and char[] in C). In expressions character arrays are implicitly converted to pointers to the first element of the arrays.

So in this statement

if ( "ben" > "BEN" )

there is a comparison pf two pointers one of which has the address of string literal "ben" and the other has the address of string literal "BEN". Usually compilers place string literals in the pool of string literals in the order in which they were encountered. So "ben" has the less address compared with the address of "BEN" because literal "ben" was found by the compiler before literal "BEN".

Take into account that even in this condition

if ( "ben" == "ben" )

the result depends of the compiler options. The compiler can store the string literals either as one string literal or as two separate string literals. So the result can be equal to either true or false.:)
Last edited on Jul 24, 2013 at 10:33am
Aug 22, 2013 at 3:27am
THANK YOU VERY MUCH for all the Responses......It is now Crystal Clear to me...

Thankyou Namaskar Spasivah....
Topic archived. No new replies allowed.