I must have missed something. I\'m doing an exercise to learn c++ and it asks that if a user inputs either c,p,t or g character then carry on, otherwise re-request prompt, so I
My understanding is that the "OR" statement should work as one of the tests is correct.
Well, you could use ||
, but the expression would have to be:
while(!(ch == 'c' || ch == 'p' || ch == 't' || ch == 'g'));
By applying the De Morgan's law, the above simplifies to:
while(ch != 'c' && ch != 'p' && ch != 't' && ch != 'g');
why is that? My understanding is that the "OR" statement should work as one of the tests is correct.
Exactly. There is always one of the tests that passes. A character will either be not 'c'
, or not 'p'
. It can't be both 'c'
and 'p'
. So the condition is always true, leading to an infinite loop.
The alternative condition with the conjunctions works because it is false as soon as ch
is equal to one of the alternatives: one of the inequalities is false, and thus the whole condition is false.