Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Negate expression containing && operator

I was making a slot machine that loops until all three std::strings 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);
like image 419
Borthamonth Avatar asked Nov 15 '16 11:11

Borthamonth


3 Answers

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

like image 173
Humam Helfawi Avatar answered Nov 05 '22 11:11

Humam Helfawi


(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))
like image 36
baddger964 Avatar answered Nov 05 '22 10:11

baddger964


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.

like image 2
Vignesh Murugan Avatar answered Nov 05 '22 10:11

Vignesh Murugan