This question already has an answer here:
I have this loop statement, which I'll express using C-like syntax (C, C++, Java, JavaScript, PHP, etc. all use similar syntax):
while (c != 'o' || c != 'x') {
c = getANewValue();
}
I want it to run until I get a 'o'
or 'x'
, but it never exits, even when c
is 'o'
or 'x'
. Why not?
I've also tried using if
:
if (c != 'o' || c != 'x') {
// Show an error saying it must be either 'o' or 'x'
}
but that also always shows the error message, even when c
is 'o'
or 'x'
. Why?
The condition
(c != 'o' || c != 'x')
can never be false. Ifc
is'o'
, thenc != 'x'
will be true and the OR condition is satisfied. Ifc
is'x'
, thenc != 'o'
will be true and the OR condition is satisfied.You want
&&
(AND), not||
(OR):"While
c
is NOT'o'
ANDc
is NOT `'x'..." (e.g., it's neither of them).Or use De Morgan's law, covered here:
"While it's NOT true that (
c
is'o'
orc
is'x'
)..."It must be
if(c!='o' && c!='x')
instead ofif(c!='o' || c!='x')
. If you use theor
operator the boolean expression will be always true.The expression combines two sub-expressions using the logical
OR
operator (||
). The expression istrue
if at least one of the sub-expressions istrue
. In order to befalse
, both sub-expressions it connects must befalse
.The sub-expressions are
c != 'o'
andc != 'x'
.The first sub-expression
c != 'o'
isfalse
whenc == 'o'
. The same for the second one; it isfalse
whenc == 'x'
.Please note that they cannot be
false
on the same time becausec
cannot be'o'
and'x'
on the same time.The condition should be
if(!(c=='o' || c=='x'))
orif(c!='o' && c!='x')
even when you enter x or you enter o in that case if condition evaluates to true and hence game_start remains false.
it should be
if(c!='o' && c!='x')
or use a more straight forward way