Reputation: 83
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);
Upvotes: 8
Views: 1461
Reputation: 1227
(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))
Upvotes: 4
Reputation: 575
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.
Upvotes: 2
Reputation: 20274
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
Upvotes: 15