Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't ("Maya" == "Maya") true in C++?

Tags:

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 Maya \n"); 
like image 894
raymond Avatar asked Jul 21 '10 19:07

raymond


1 Answers

Because you are actually comparing two pointers - use e.g. one of the following instead:

if (std::string("Maya") == "Maya") { /* ... */ }  if (std::strcmp("Maya", "Maya") == 0) { /* ... */ } 

This is because C++03, §2.13.4 says:

An ordinary string literal has type “array of n const char

... and in your case a conversion to pointer applies.

See also this question on why you can't provide an overload for == for this case.

like image 135
Georg Fritzsche Avatar answered Sep 27 '22 20:09

Georg Fritzsche