Using the equality operator == to compare two strings for equality in C

前端 未结 9 606
悲&欢浪女
悲&欢浪女 2020-11-22 16:38
int main (int argc, **argv)
{
       if (argv[1] == \"-hello\")
            printf(\"True\\n\");
       else
            printf(\"False\\n\");
}
         


        
9条回答
  •  悲哀的现实
    2020-11-22 17:18

    In C because, in most contexts, an array "decays into a pointer to its first element".

    So, when you have the array "foobar" and use it in most contexts, it decays into a pointer:

    if (name == "foobar") /* ... */; /* comparing name with a pointer */
    

    What you want it to compare the contents of the array with something. You can do that manually

    if ('p' == *("foobar")) /* ... */; /* false: 'p' != 'f' */
    if ('m' == *("foobar"+1)) /* ... */; /* false: 'm' != 'o' */
    if ('g' == *("foobar"+2)) /* ... */; /* false: 'g' != 'o' */
    

    or automatically

    if (strcmp(name, "foobar")) /* name is not "foobar" */;
    

提交回复
热议问题