C - while (something || something)
I have a quick question about while loop.
I want to read ASCII char code and if it's not some particular ascii code I don't want to continue and ask user to enter it again.
This works
while (yn != 89)
开发者_StackOverflow社区 {
printf("\nEnter");
flushall();
scanf("\n%c", &yn);
}
This does not
while (yn != 89 || yn != 121)
{
printf("\nEnter");
flushall();
scanf("\n%c", &yn);
}
Gosh, I think I need to get some sleep. This was rather... stupid. :) Thanks guys BTW.
The expression yn != 89 || yn != 12
is always true. Any value is either not equal to 89
or not equal to 12
. So, this expression makes no practical sense. The cycle will loop forever, since the repetition condition is always true.
According to your description, the condition you need is yn != 89 && yn != 12
. &&
, not ||
.
Your boolean logic is a bit off:
while (yn != 89 && yn != 121)
Another way to write this, which may be more logical as a "reader":
while (!(yn == 89 || yn == 121))
Replace || with &&.
The reason:
!(yn == 89 || yn == 121)
<==> yn != 89 && yn != 121
(DeMorgan)
When yn
is 89 it is not 121
; similarly when yn
is 121, it is not 89; thus, the condition is always satisfied.
Perhaps you mean while yn
is not either 89
or 121
, that's phrased with an and:
while(yn != 89 && yn != 121)
or alternatively you can say "when yn
is neither 89
or 121
":
while( !(yn == 89 || yn == 121) )
To expand a little on the other replies - you will never get to your second condition. The first "short-circuits"
if (yn != 89
And stop right there. If it's not 89, we're done. We don't care about anything after that in the if
because ||
(OR) is "If either of these is the case". And of course, if it IS 89 ... then it's certainly not 121.
You want while (yn != 89 && yn != 121)
The inverse of (A || B)
is (!A && !B)
and the inverse of (A && B)
is (!A || !B)
. Your thought process in constructing the original loop was something like, "I want yn == 89
, so I should invert that to loop while yn != 89
." Then you decided to change it to, "I want yn == 89 || yn == 121
, so I need to invert that." That's where you went wrong: From the forms I presented originally you can see the inverse (to use as your while condition) is yn != 89 && yn != 121
. You simply extended your original, simple inversion with ||
inappropriately.
精彩评论