Search code examples
c++stringcommutativity

Should you use (x == "x") or ("x" == x) to compare strings?


What is the difference between (x == "x") and ("x" == x) comparison in C++? Let's say x is a std::string. Is there any reason why one would be preferred over the other?


Solution

  • One is a string literal "X", and the other is an instance of std::string. Some advocate having the constant "x" on the left hand side, because that way you would get a compiler error if you use assignment = instead of equality ==:

    if ("x" = x) // Error! Trying to assign to const char[]
    
    if (x = "x") // Setting the value of x to be "x", and evaluating "x". 
                 // Probably not what you want.
    

    Other than that, there's really no difference.