If statement

Greetings. I'm having a problem with an if statement, and I was wondering if you could help me out.

1
2
3
4
5
if ( xTest + 11 == 11 && yTest == 4 || yTest == 6 || yTest == 8)

{
cout << "nice"
}


It seems to execute the right part even though that the xTest + 11 doesn't equal 11, how come?

Last edited on
I think this is a parenthesis problem as it evaluates left to right so if xTest = 1 and yTest = 6,
1
2
3
4
if(xTest+11 == 11 //false
   && yTest == 4 //false
   || yTest == 6 //true
   || yTest == 8) //false 

is the same as
 
if(false && false || true || false)

which evaluates to
 
if(false||true||false)

which evaluates to
 
if(true||false)

which evaluates to
 
if(true)
You need to be careful when you mix the && and || operations. I suggest you use parentheses to insure the logic is evaluated like you think it should be.

Alright, I think I get it. So how do I make it so that if the first part of the if statement (xTest + 11 == 11) is false then ignore the rest?
if(xTest==0 && (yTest==4||yTest==6||yTest==8))
Last edited on
Topic archived. No new replies allowed.