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

前端 未结 9 598
悲&欢浪女
悲&欢浪女 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:23

    Because C strings dont exist as such. They are char arrays ending in a \0.

    The equality operator == will test that the pointer to the first element of the array are the same. It wont compare lexicographically.

    On the other hand "-hello" == "-hello" may return non zero, but that doesn't mean that the == operator compares lexicographycally. That's due to other facts.

    If you want to compare lexicographycally, you can always

    #define STR_EQ(s1,s2)    \
       strcmp(s1,s2) == 0
    

    Reading harder I see that you tagged as c++. So you could

     std::string arg1 ( argv[1] );
    
     if (arg1 == "-hello"){
        // yeahh!!!
     }
     else{
        //awwwww
     }
    
    0 讨论(0)
  • 2020-11-22 17:23

    Strings are not native types in C. What you are comparing in that example are two pointers. One to your first argument, and the other is a static character array with the contents of "-hello".

    You really want to use strncmp or something similar.

    0 讨论(0)
  • 2020-11-22 17:25

    You can't compare strings in C with ==, because the C compiler does not really have a clue about strings beyond a string-literal.

    The compiler sees a comparison with a char* on either side, so it does a pointer comparison (which compares the addresses stored in the pointers)

    0 讨论(0)
提交回复
热议问题