OR operator in while loop

Jan 31, 2012 at 11:25pm
This is driving me crazy, I want the loop to exit when the user chooses '3' or when Enemy.HP is 0 or lower. What's wrong with my while loop?

1
2
3
4
5
6
7
8
9
10
do 
	{
		DisplayMenu();
		cin >> choice;
		switch (choice) {
			case 1: Enemy.changeHP(-(Player1.AD));  break;
			case 2: Enemy.showStats();  break;
			case 3: break;
		}
	} while ((choice != 3) || (Enemy.HP > 0));
Jan 31, 2012 at 11:28pm
If either condition evals as true, the whole statement is true.

Even if the user presses 3, if Enemy.HP is > 0, it will continue to run and vice versa. If HP < 0 and the player has not pressed three, it will continue to run.

You may need to invert the condition and evaluate it for when it's not true.
Last edited on Jan 31, 2012 at 11:30pm
Jan 31, 2012 at 11:31pm
I think you would like to use && instead of ||
Jan 31, 2012 at 11:34pm
+1 roberts.

Remember that the loop condition is the condition for continuing the loop, not for exiting it.

If the exit condition is "user chooses '3' or when Enemy.HP is 0 or lower"...

... then the continue condition is "user does not choose 3 and enemy HP is higher than 0"

Alternatively, the continue condition is !( /*exit condition*/ )

So...

1
2
3
4
5
while( (choice != 3) && (Enemy.HP > 0) );

// or alternatively:

while( !( (choice == 3) || (Enemy.HP <= 0) ) );
Last edited on Jan 31, 2012 at 11:35pm
Jan 31, 2012 at 11:47pm
Thanks a bunch, that cleared things up. I think I had what condition I was using mixed up in my head.
Last edited on Jan 31, 2012 at 11:47pm
Topic archived. No new replies allowed.