comparison between string literal

前端 未结 4 885
后悔当初
后悔当初 2020-11-30 12:25

This very simple code:

#include 

using namespace std;

void exec(char* option)
{
    cout << \"option is \" << option << e         


        
相关标签:
4条回答
  • 2020-11-30 12:28

    char arrays or char pointers aren't really the same thing as string class objects in C++, so this

    if (option == "foo")
    

    Doesn't compare the string option to the string literal "foo" it compares the address of option with the address of the string literal "foo". You need to use one of the many string comparison functions if you want to know if the option is the same as "foo". strcmp is the obvious way to do this, or you can use std::string instead of char*

    0 讨论(0)
  • 2020-11-30 12:36

    The reason why it doesn't work is because the comparison does not compare strings, but character pointers.

    The reason why it may work when you use char* is because the compiler may decide to store the literal string "opt" once and reuse it for both references (I am sure I have seen a compiler setting somewhere that indicates whether the compiler does this).

    In the case of char opt[], the compiler copies the string literal to the storage area reserved for the opt array (probably on the stack), which causes the pointers to be different.

    Renze

    0 讨论(0)
  • 2020-11-30 12:41

    You can use == operator to compare strings only if you use std::string (which is a good practice). If you use C-style char*/char[] strings, you need to use C functions strcmp or strncmp.

    You can also use the std::string::operator == to compare std::string with a C string:

    std string foo = "foo";
    const char *bar = "bar";
    
    if (foo == bar) 
       ...
    
    0 讨论(0)
  • 2020-11-30 12:41

    For C++ I would use the std::string solution:

    #include <iostream> 
    #include <string>
    
    using namespace std; 
    
    void exec(string option) 
    { 
        cout << "option is " << option << endl; 
        if (option == "foo") 
            cout << "option foo"; 
        else if (option == "bar") 
            cout << "option bar"; 
        else 
            cout << "???"; 
        cout << endl; 
    } 
    
    int main() 
    { 
        string opt = "foo"; 
        exec(opt);
    
        exec("bar");
    
        char array[] = "other";
        exec(array);
        return 0; 
    } 
    

    std::string knows how to create itself out of char[], char*, etc, so you can still call the function in these ways, too.

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