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

前端 未结 8 1353
野趣味
野趣味 2020-12-29 05:21

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         


        
8条回答
  •  春和景丽
    2020-12-29 05:35

    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.

提交回复
热议问题