3
do { cout << "Car is coming ... " << "[P]ay or [N]ot?" << endl; ch=getch(); } while ( ch !='q' || ch != 'Q'); 

Why will the code on top not work while the code below does? I tried it with parenthesis around each statement in numerous ways and the compiler would pop an error every time until I regrouped them as I did below. I'm just wondering why it does this.

do { cout << "Car is coming ... " << "[P]ay or [N]ot?" << endl; ch=getch(); } while ( !(ch=='q' || ch=='Q') ); 

I'm using Visual Studio 2008 as my compiler; x86 architecture.

1
  • 3
    P.S.: What game is this? Sounds like Crazy Taxi. :-) Commented May 23, 2011 at 23:28

7 Answers 7

16

Learn De Morgan's laws

(not A) or (not B)

is not the same as

not (A or B).

Sign up to request clarification or add additional context in comments.

Comments

3

(ch != 'q' || ch != 'Q') is always true: "ch is not equal to 'q' or ch is not equal to 'Q'".

Comments

2

The problem is your boolean logic is off and the two while conditions are not the same.

  • Top: Character is not 'q' or is not 'Q'
  • Bottom: Character is not ('q' or 'Q')

The Top will return true for every single character possible. The bottom will return true for every character except 'q' and 'Q'

Comments

0

I think you want this in your first example:

ch !='q' && ch != 'Q' 

You want that the input is not q AND not Q.

Comments

0

!(ch=='q' || ch=='Q') is equivalent to ch!='q' && ch!='Q'. See also De Morgan's laws.

Comments

0

You've got the logic backwards, that's my negating it works. By DeMirgan's laws, !(ch == 'Q' || ch == 'q') is the same as ch != 'Q' && ch != 'q'.

Since a if it cannot be both little q and big Q at the same time, while (ch != 'Q' || ch != 'q') doesn't make sense because if it is 'Q' then it won't be 'q', and vice versa.

Comments

0

When inverting all your logic using '!', you did right by reversing the conditional operators "==" to "!=", but you forgot to reverse the logical operators "||" to "&&". Thus, this should be correct:

while (ch!='q' && ch!='Q'); 

I use C#, so while code above will work, I would have used this instead as it is easier to read:

while (ch.ToUpper() != 'Q'); 

1 Comment

Thanks, I'm probably going to use a similar function to ToUpper() in the future.