I was making a slot machine that loops until all three std::string
s have the same value. I'm confused as to why in this code the || operator
is giving the desired result rather than the && operator
.
std::string slotA,slotB,slotC;
do {
//Fill slotA, slotB and slotC with some data
} while (slotB != slotC || slotB != slotA);
Your stop condition should be:
while (!(slotB == slotC && slotB == slotA));
However, in Bool-Algebra !(slotB == slotC && slotB == slotA)
is equal to slotB != slotC || slotB != slotA
This rule is called De Morgan Law
(slotB != slotC || slotB != slotA)
Is the good way to do your work.
A little example if you use :
(slotB != slotC && slotB != slotA)
usuming :
slotA = Banana
slotB = Banana
slotC = Apple
so :
(slotB != slotC && slotB != slotA)
(Banana != Apple && Banana != Banana)
( true && false)
( false )
The while loop end with a bad guesses.
In your case it's maybe more simple to write the condition for a good guesses and take the negative, like Humam Helfawi says :
while (!(slotB == slotC && slotB == slotA))
I think there is possibility that two strings are same and third one different which might make you loop condition fail if you use &&(and) operator.
i.e. slotA
and slotB
might me equal which makes slotA != slotB
a false statement and it will come out of the loop. but when you use ||
condition the slotC != slotB
is true and it continues the loop.
Note: This is one of the possibility but might not be the actual reason.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With