简体   繁体   中英

Confusion with the OR logical Operator in a Loop

A bit earlier on an IRC channel, someone asked a question about his code - essentially, his program was running on an infinite loop:

#include <iostream>
using namespace std;

int main()
{
cout << "This program adds one to your input." << endl;

char choice = 'n';
int num = 0;

while (choice != 'y' || choice != 'Y')
{

    cout << "Enter number: ";

    cin >> num;
    num++;
    cout << "Your number plus 1 is: " << num << endl;
    cout << endl << "Continue/Quit? Type 'Y' to quit, any other key to continue: ";

    cin >> choice;
}

cout << "By choosing 'Y', you exit the loop." << endl;

return 0;

}

Paying attention to the loop header, it seems that the loop should be working perfectly fine, but whenever it comes time for me to enter Y or y in order to exit, the loop keeps running. Considering that the while loop won't evaluate the expression to the right if the one on the left is true, this makes it especially confusing. But in any case, even if I input Y or y the loop keeps running! I'd like a somewhat in-depth explanation of why this happens, I've been trying to reason it out, look back in my textbook etc. but I can't seem to understand why... I've changed the OR into an AND, but what makes OR so bad and causes it to malfunction?

Thanks all.

Condition (choice != 'y' || choice != 'Y') is always true, so loop will run indefinetely. If choice == 'y', then you get (false || true) == true; if choice == 'Y', then you get (true || false) == true. You need to use while(choice != 'y' && choice != 'Y') instead, in this case you exit loop only if you get 'y' or 'Y', otherwise you get (true && true) and continue.

The OR operator between many statements returns true if at least 1 of the statements is true, no matter if the others are false or true. In your case, choice != 'y' || choice != 'Y' choice != 'y' || choice != 'Y' will be evaluated like this:

First statement is true: Execute while loop.

First statement is false: Check if the second statement is true.

Second statement is true: Execute while loop.

Second statement is false: don't execute while loop.

Specifically, when the compiler arrives at choice != 'y' , if choice == 'Y' , then it will still execute, because choice != 'y' is true, in fact choice is equals to Y , so it's different from y .

If, on the other hand, choice is equals to y , then it will check if the second statement is true, but we know that choice is equals to y , so choice is different from Y , and so on...

You make a mistake,you should change "||" to "&&"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM