i dont understand why this code behavies the way it does

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <limits>

using namespace std;

int main(int argc, char *arv[])
{

	cout << "enter 1 or 2: ";
	int response;
	cin >> response;

	if ((response != 1) || (response !=2))
		cout << "you must enter 1 or 2";

	cin.sync();
	cout << endl;
	cout << "Press ENTER to continue...";
	cin.ignore(numeric_limits<streamsize>::max(), '\n' );
}


by reading it i would think the if statement would fire if the response was not equal to one or not equal to 2. yet the if statement fires when i respond with 1. why is that.
Last edited on
Use an and. &&

If response is not 1 or is not 2, invalid number. Will always be true.
Last edited on
ok || doesnt work like i think it did. i thought it meant 1 or the other. as in 1 = true or 2 = true results in true only if one or the other is true.
It does mean one or the other, you're including every number except one, with two numbers. One value cannot be two at once.

1
2
3
4
int value = 4;

if (value == 4 && value != 4)
   //Similar circumstance, will never happen, impossible 
Last edited on
i will have to look at it over because it still doesnt make sense to me. if it says true condition if not 1 or not 2 then why would it also be true if i type 1.
Consider it this way. Let's say you input 1:
- Is 1 not equal to 1? No
- Is 1 not equal to 2? Yes
- Is one OR the other true? Yes, we run the if statement.

Let's say you input 2:
- Is 2 not equal to 1? Yes
- Is 2 not equal to 2? No
- Is one OR the other true? Yes, we run the if statement.

Any other number:
- Is X not equal to 1? Yes
- Is X not equal to 2? Yes
- Is one OR the other true? Yes, we run the if statement.

As you can see, the statement is always true.
thanks zhuge i feel like an idiot now.
Topic archived. No new replies allowed.