0

Suppose I have:

QString x;

Is the following code fragment:

if(x.compare("abcdefg") == 0){
  doSomething();
}
else{
  doSomethingElse();
}

... functionally equivalent to:

if(x == "abcdefg"){
  doSomething();
}
else{
  doSomethingElse();
}

I could prove this for myself by writing a fairly trivial program and executing it, but I was surprised I couldn't find the question / answer here, so I thought I'd ask it for the sake of future me / others.

2
  • 2
    That's fine, but what has the QVariant got to do with anything? You're operating on a QString instance, the fact that you got it from QVariant is quite immaterial here because you obtain it the same way in both cases. It doesn't even matter that canConvert<QString> returns true. You'll get valid results when it returns false, too. Besides, why do you care what compare returns? You want to compare strings, use the operator==, it's what it's for. Commented Sep 9, 2016 at 18:33
  • @KubaOber you're right, I've removed the QVariant distractions Commented Sep 9, 2016 at 20:11

1 Answer 1

3

QString::compare will only return zero if the string passed to it and the string it is called on are equal.

Qstring::operator== returns true if the strings are equal otherwise, false.

Since compare only returns zero when the strings are equal then

(qstrign_variable.compare("text") == 0) == (qstrign_variable == "text")

If qstrign_variable contains "text" in the above example. If qstrign_variable contains something else then both cases evaluate to false.

Also note that std::string has the same behavior

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.