Any idea why I get \"Maya is not Maya\" as a result of this code?
if (\"Maya\" == \"Maya\")
printf(\"Maya is Maya \\n\");
else
printf(\"Maya is not Ma
Any idea why i get "Maya is not Maya" as a result
Because in C, and thus in C++, string literals are of type const char[]
, which is implicitly converted to const char*
, a pointer to the first character, when you try to compare them. And pointer comparison is address comparison.
Whether the two string literals compare equal or not depends whether your compiler (using your current settings) pools string literals. It is allowed to do that, but it doesn't need to. .
To compare the strings in C, use strcmp()
from the
header. (It's std::strcmp()
from
in C++.)
To do so in C++, the easiest is to turn one of them into a std::string
(from the
header), which comes with all comparison operators, including ==
:
#include
// ...
if (std::string("Maya") == "Maya")
std::cout << "Maya is Maya\n";
else
std::cout << "Maya is not Maya\n";