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?
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.