gamedynamix
gamedynamix

Reputation: 33

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?

Upvotes: 3

Views: 576

Answers (3)

Lstor
Lstor

Reputation: 2263

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.

Upvotes: 5

user387184
user387184

Reputation: 11053

I prefer using for NSStrings...

([x isEqualToString:@"x"]) 

or for c strings

strcmp(str1,str2);

Upvotes: 0

beduin
beduin

Reputation: 8253

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.

Upvotes: 1

Related Questions