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?
Should you use (x == "x") or ("x" == x) to compare strings?
567 Views Asked by gamedynamix At
3
There are 3 best solutions below
1
On
I think both calls will result in call to bool std::string operator==(const std::string&, const std::string&).
This is because there are no implicit conversion operators from std::string to const char*, but there is implicit constructor from const char* to std::string.
EDIT:
on g++ 4.4.5 both comparisons works.
One is a string literal
"X", and the other is an instance ofstd::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==:Other than that, there's really no difference.