if statement problem

Hello,



if (choice != choicea || choiceb)
{
do something
}

i would think this logic would work but it doesn't. The point of the app is to get a value and then if the choice is not equal to either choicea or choiceb, do something.

why doesn't this work the choicea and choiceb does not equal to the choice....

help??
I'm no expert but I can diagnose some basic errors:
You cannot just refer to a variable and expect the compiler to assume the operation. When you write choiceb you think of it as english, and too literally:
if choice does not equal choice a or choice b
But the compiler does not think that way and needs you to be rather clearer:
if (choice != choicea || choice != choiceb)
{
}


That code still won't satisfy your condition because I think you misinterpret the || operator, you should use &&. You want something to happen only if the choice equals neither choicea or choiceb. If you use or, the expression will always return true because choice cannot equal both choicea and choiceb simultaneously; therefore one of the != expressions will be true and the whole expression must also be true. You need the && operator because that way you will check both the != conditions, and will only return true if they both do not equal the desired choices.

Therefore your final code should look more like this (changes in bold):
if (choice != choicea && choice != choiceb)
{
// Actions here
}


EDIT: You may want to take a look at this article for further guidance:
http://www.cplusplus.com/forum/articles/3483/
Last edited on
Topic archived. No new replies allowed.