ni**********@yahoo.com posted:
I'm working on a project for my c++ class and I am having trouble
comparing one string to two others using the or operator. It looks
something like this:
if(answer3 == answer1 || answer2)
Is there another command I need to through in there or should I do it a
completely different way?
Any suggestions would be most appreciated.
You've written that because English is your native language, and that's
how you would have said it:
If answer3 is equal to answer1 or answer2, then blah blah blah...
C++ doesn't talk like that. It talks like so:
If answer3 is equal to answer1, or if answer3 is equal to answer2, then
blah blah blah...
if ( (answer3 == answer1) || (answer3 == answer2) ) blah blah...
The obvious difference is that we have two separate equality tests. I'll
show you what your original code does:
if(answer3 == answer1 || answer2)
The equality operator has higher precedence than the Logical OR operator,
and so it's evaluated first. It returns a value which is "bool" (ie.
"true" if they're equal, "false" if they're not equal).
So first it compares answer3 to answer1, and yields a "bool" value. Let's
say this value is "true".
Next thing is that the Logical OR operator is evaluated. On the left of
it, we have "true", and on the right we have "answer2". "answer2" must be
able to convert to a "bool" in order for this operation to take place. If
it can't, you'll get a compile error. But let's say it can, and that it's
converted to "false".
Then you'll have (false || true) which turns out to be "true".
(In actual fact, there was no need to carry out the processing of the
second part, because the first part was found to be "true", and so the
entire expression had to evaluate to "true", regardless of the second
value involved).
-Tomás