开发者

String compare in c++

开发者 https://www.devze.com 2023-03-01 15:52 出处:网络
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 str

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.


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.


Here says the now closed question on Yoda Conditionals:

This is one of the things that I hate most when I see it in someone else's code. I know what it means and why some people do it this way ("what if I accidentally put '=' instead?"). For me it's very much like when a child goes down the stairs counting the steps out loud.

Anyway, here are my arguments against it:

  • It disrupts the natural flow of reading the program code. We, humans, say "if value is zero" and not "if zero is value".
  • Modern compilers warn you when you have an assignment in your condition, or actually if your condition consists of just that assignment, which, yes, looks suspicious anyway
  • You shouldn't forget to put double '=' when you are comparing values if you are a programmer. You may as well forget to put "!" when testing non-equality.

-mojuba


Accepted answer:

Ah, yes, "Yoda conditionals" ("If zero the value is, execute this code you must!"). I always point anyone who claims they're "better" at tools like lint(1). This particular problem has been solved since the late 70s. Most modern languages won't even compile this, as they refuse to coerce the result of the assignment to a boolean.

As others have said, it certainly isn't a problem, but it does provoke a bit of cognitive dissonance.

-TMN


I prefer using for NSStrings...

([x isEqualToString:@"x"]) 

or for c strings

strcmp(str1,str2);


There is no difference between those two conditions, other than maybe something internal. It's like holding two things in your hands, one in each hand, and comparing them - and then basing then factoring in which hand each one is in. ...That's not something that's a factor.

0

精彩评论

暂无评论...
验证码 换一张
取 消