If statement
May 29, 2015 at 2:58pm UTC
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 May 29, 2015 at 2:58pm UTC
May 29, 2015 at 3:15pm UTC
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
which evaluates to
which evaluates to
May 29, 2015 at 3:24pm UTC
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.
May 29, 2015 at 3:25pm UTC
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?
May 29, 2015 at 4:04pm UTC
if (xTest==0 && (yTest==4||yTest==6||yTest==8))
Last edited on May 29, 2015 at 4:04pm UTC
Topic archived. No new replies allowed.