0

I am trying too add every element in a int matrix so I can check if the player or computer wins.

bool WinCondition(int Grid[10][10])
{
    int SumOfShips;
    for (int a = 0; a < 10; a++)
    {
        for (int b = 0; b < 10; b++)
        {
            SumOfShips += Grid[a][b] ;
            if (SumOfShips == 30) return true;
        }
    }
    return false;
}

However "+=" isn't working for me neither is . . . = Grid[a][b] + SumOfShips, I am getting the error "unititialized local variable 'SumOfShips' used"

  • Local variables are never initialized unless you explicitly do it. Uninitialized local variables will have an *indeterminate* value, and using such values in C++ leads to *undefined behavior*. – Some programmer dude Apr 18 '21 at 11:11

2 Answers2

0

As the message says, the variable SumOfShips is used without being initialized.

Initialize that like this:

int SumOfShips = 0;

instead of:

int SumOfShips;
MikeCAT
  • 73,922
  • 11
  • 45
  • 70
0

You need to have int SumOfShips = 0; or some initial value, which makes sense in the context.

The reason being, that SumOfShips, when not initialized holds an arbitrary (indeterminate) value given the randomly assigned memory location.

Further, the uninitialized value is regarded as being 'indeterminate', check here for a more thorough explanation.

ms99
  • 61
  • 4