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

前端 未结 8 1351
野趣味
野趣味 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:38

    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";
    

提交回复
热议问题