Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

noob question c++

Name: Anonymous 2009-07-12 13:15

Why doesn't this work?

#include <iostream>
using namespace std;
int main(int argc,char** argv){
   string name;
   cout<<"What is your name?"<<endl;
   cin>>name;
   if(name=="Anonymous")
   cout<<"Aw don't be shy..."<<endl;
   else
   cout<<"Hello "<<name<<"!"<<endl
   return 0;
}

Name: Anonymous 2009-07-12 20:31

>>9
What the fuck? That's not what happens at all. There is no implicit cast from string to int; the compiler won't magically take the address of your string. There is an implicit cast from char* to string (due to string's implicit char* constructor), so that's what you will get, and the comparison will work.

You're thinking of comparing string* to char*. If you did this:

std::string* str = new std::string("Anonymous");
cout << (str == "Anonymous");

then yes, it would fail, because the pointers are compared, because in this case 'str' is a pointer type.

To answer >>8's question, yes == is overloaded (as well as < and >), and they will work comparing string to char*, but they will NOT work comparing string* to char*. You have to make sure you're not comparing pointers; if you have string pointers you have to dereference them.

But if you're doing things properly you should never, ever have string pointers anyway. If the overhead of copy constructors is a problem for you, you shouldn't be using stl string. In 99% of applications, the right thing to do is not worry about it and not let it bother you. Trust the compiler to do return value and related optimizations, and trust the allocator to do its job.

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List