Why is this an infinite loop using ||logical operator
char c;
std::cin >> c;
while( c != 'y' || c != 'Y' || c != 'N' || c != 'n')
but this is not
while( c != 'y' && c != 'Y' && c != 'N' && c != 'n')
I don't understand why && operator work here because logically thinking || operator is better fit.
Lets just look at the very smallest part:
c != 'Y' || c != 'N'
If c is 'Y' then it is not 'N', if it is 'N' then it is not 'Y'. Aka:
c | c != 'Y' || c != 'N'
Y | 1 || 0 = 1
N | 0 || 1 = 1
? | 1 || 1 = 1
If your logic always returns 1 no matter what, the loop will run forever. I assume you are looking to wait until you get c
as one of these values, so write it logically.
I want to wait until c is one of ['y', 'Y', ...]
And you might be able to write some nicer code:
std::array<char> options = {{'y', 'Y', 'n', 'N'}};
while (std::none_of(std::begin(options), std::end(options),
[&c](char check) { return check == c; };)) {
std::cout << "Hey write the correct character!\n";
}
Untested!
You are checking the condition which is always true by using ||
operator, ( c != 'y' || c != 'Y' || c != 'N' || c != 'n')
This is always true,because it would always satisfy at-least 3 conditions in your conditional statement.
if your char is n
then it would satisfy remaining conditions c!='y'
, c!='Y'
, c!='N'
and similarly for any other character
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.