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

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

    You are not comparing strings, you are comparing pointer address equality.

    To be more explicit -

    "foo baz bar" implicitly defines an anonymous const char[m]. It is implementation-defined as to whether identical anonymous const char[m] will point to the same location in memory(a concept referred to as interning).

    The function you want - in C - is strmp(char*, char*), which returns 0 on equality.

    Or, in C++, what you might do is

    #include

    std::string s1 = "foo"

    std::string s2 = "bar"

    and then compare s1 vs. s2 with the == operator, which is defined in an intuitive fashion for strings.

提交回复
热议问题