Home > Software design >  c 2D Array in If statement logic failing tic-tac-toe
c 2D Array in If statement logic failing tic-tac-toe

Time:08-30

TLDR: I am making a tic tac toe game in c . My win condition checking if statements are failing and I don't know why :(

The board state is maintained by a global 2D board array

int board[3][3]{ {0,0,0}, {0,0,0}, {0,0,0}};

As the game plays on, a 1 or 2 is inserted to represent an X or O. Periodically I check for a winner with a function that uses 8 if statements to check for win conditions (3 horizontals, 3 verticals, or 2 diagonals).

int winCheck()
{
    int winner = 0;
    
    // check horizontal 1
    if ((board[0][0] == board[0][1] == board[0][2]) && (board[0][2] > 0))
    {
        winner = board[0][0];
    }

    // check horizontal 2

    ...

    return winner;
}

Any ideas? I think the logic is fine but my syntax is off.

CodePudding user response:

Sigh. After pulling my brain out for 4 hours. It appears that you can't logically compare 3 things in an if statement ie:

if (A == B == C)

You must instead do 2 comparisons...

if (A == B && B == C)

Maybe this will help someone someday...

  • Related