If-Then with && and || passes when it shouldn't

I'm introducing myself to C++ and have been working on a Tic-Tac-Toe program.
I'm using #include <stdio.h>
My large amount of block if-then statements sometimes passes when it shouldn't.
I have an idea as to why but I'm sure it's wrong because it doesn't always occur. I think it should be right but --obviously-- it isn't.

Here's the code that causes the problem(s):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
	if(area[0][0] && area[0][1] && area[0][2] == 'X' || area[1][0] && area[1][1] && area[1][2] == 'X' || area[2][0] && area[2][1] && area[2][2] == 'X')
		{
		winner = 'X';
		goto victory;
		}
	if(area[0][0] && area[1][0] && area[2][0] == 'X' || area[0][1] && area[1][1] && area[2][1] == 'X' || area[0][2] && area[1][2] && area[2][2] == 'X')
		{
		winner = 'X';
		goto victory;
		}
	if(area[0][0] && area[1][1] && area[2][2] == 'X' || area[2][0] && area[1][1] && area[0][2] == 'X')
		{
		winner = 'X';
		goto victory;
		}

Last edited on
You're using && and || the wrong way. && will evaluate if both terms on its Immediate left and right are true (non-zero).

So something like this:
 
if(area[0][0] && area[1][1])

Evaluates to true if area[0][0] and area[1][1] are both non-zero.
You want something like this:
1
2
3
4
if((area[0][0]=='X' && area[1][1] == 'X' && area[2][2] == 'X') || etc...)
{
 Winner = 'X';
}

Also, try to avoid "goto", it's generally considered bad programming practice since it makes it hard to follow your code. Just use an if...else block:
1
2
3
4
5
6
7
8
9
10
11
12
13
if(condition1)
{

}
else if(condition2)
{

}
else if(condition3)
{

}
etc...


EDIT: Just a clarification, || works just as I described &&, but in this case it evaluates to true if either term or both are non-zero/true. So we put the whole area[0][0] == 'x' && etc... in a pair of parenthesis so that it evaluates first, and then or it with the next "condition block".

EDIT2: You could also just test like this:
 
if(area[0][0] == area[1][1] == area[2][2] == 'X')
Last edited on
I usually try to shy away from goto but I can't think of a way to go from point A to point B and back to point A within the same function.

But... I suppose I think I can do something like this as long as I dim the variables globally
1
2
3
4
5
6
7
8
9
10
11
12
13
main()
{
...etc...
something();
something_return:
...etc...
}

something()
{
...etc...
goto something_return;
}


Thanks for the help, I appreciate it.

EDIT: Wait, I can't do that. Goto has to be within the function.
Last edited on
http://www.cplusplus.com/doc/tutorial/control/ and next
When the function ends, the flow is returned to the caller, and the next line is executed.

EDIT2: You could also just test like this:
if(area[0][0] == area[1][1] == area[2][2] == 'X')
No, you can't. It's the same issue.
So we put the whole area[0][0] == 'x' && etc... in a pair of parenthesis so that it evaluates first
There is no need (precedence rules)
Topic archived. No new replies allowed.