problem with string compare

#include
#include
int main()
{
using namespace std;
char foo[]="hello";
char bar[]="hello";
if(foo==bar)
cout<<"equal";
else cout<<"not equal";
return 0;}

#include<iostream>
#include
int main()
{
using namespace std;
string foo="hello";
string bar="hello";
if(foo==bar)
cout<<"equal";
else cout<<"not equal";
return 0;}





why different results are coming?



Comments

  • In the first case foo[] and bar[] are pointers (Like foo * and bar *). They're holding 2 different memory address. On both addresses in memory is the same data "hello".
    With foo==bar, you compare the TWO MEMORY ADDRESS, and they're different.

    With string, foo and bar is a std::string object. String objects have their own compare function.
    With foo==bar you invoke the string's compare function, which compares THE DATA IN THE STRINGS, and they are the same ("hello")

    Hope it helps:
    Imre Horvath
  • Oh,I'm studying C++ too.Any software can help???
    -----------------------------------------------------
    [u]Software Outsourcing[/u][color=Blue][/color]
  • This post has been deleted.
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories