6

I currently have a method called getResult which returns const char* now I am doing something like this

if(getResult=="Something")
{
  ...
}

However it seems this type of comparison doesn't work. Isn't "Something" also a const char pointer ? or in this case are the addresses being compared?

Casper_2211
  • 1,075
  • 5
  • 14
  • 25

3 Answers3

6

Yes, the addresses are being compared. To compare the contents of two strings, use the strcmp function:

if (strcmp(getResult, "Something") == 0) {
    ...
}
5

If getResult is a method (member function) you need to call it to compare the result, so you probably want:

if (something.getResult() == std::string("Something"))
  // ...

If, on the other hand, getResult is really a pointer to char (or pointer to const char), you need to convert one of the things you're comparing to string before the comparison):

if (getResult == std::string("Something"))

or:

if (std::string(getResult) == "something))

IMO, this should almost never be necessary -- instead of starting with a pointer to [const] char, then converting, you should normally use std::string throughout.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
2

If you compare 2 string constants in C/C++ you compare the actual address of each string, not the content. Using strcmp on 2 c-strings or using C++'s std::string class will compare the content.

bash0r
  • 605
  • 1
  • 7
  • 16