I am having trouble understanding the logic of a couple of logical operators.
I will show you an example in a context below that will (hopefully) illustrate my confusion.
Take this snippet of code for example:
1 2 3 4 5 6 7 8
|
cout << "Choose either a or b";
cin >> choice;
while (choice != 'a' && choice != 'b')
{
cout << "Wrong choice, try again ";
cin >> choice;
}
|
As you can see, what I am (successfully) doing here is prompting the user for input for as long as he/she does NOT enter a or b. Once a or b is entered, the program continues as it should.
Now, while the previous example works (I found that out the hard way via trial and error and a lot of swearing), the example below does not:
1 2 3 4 5
|
while (choice != 'a' || choice != 'b') // The difference is the || operator
{
cout << "Wrong choice, try again ";
cin >> choice;
}
|
I guess I could just be pleased with the fact that the first example works, and the latter doesn't. But I am not. I want to understand why. Because; to me it seems like the latter example makes much more sense – logically, than the first. I want to use the || operator, because supposedly it equals ”or”. In pseudo code (to me) the last example looks like:
While user does not enter 'a' OR 'b';
do the loop.
This seems logical to me, but it doesn't work. The first example in pseudo code looks to me like:
While user does not enter 'a' AND 'b';
do the loop.
This does not make sense to me, it seems illogical, but it works!
I hope you understand my ramblings. Like I said, this is not ”a problem” as such. I have found the right way to do it – now what I really want to know is
why it works!!!
Thanks for reading this,
HMW