I've been told that I should always avoid using
continue
to avoid creating spaghetti code. Are there situations where it is appropriate?
For fun I've been trying to recreate the classic minesweeper game. When the user selects a cell, that cell is revealed. If the cell is not adjacent to any mines, it will also reveal the cells around it. I've written a recursive function to emulate this. In the function I use a
continue
to skip revealing the current cell that is already being revealed.
If I wanted to remove the continue, how would I do this?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
void reveal_cell(int x, int y)
{
if (grid[x][y].hidden == false) return; //Avoid doing touching a cell that's been revealed.
grid[x][y].hidden = false; //Reveal the cell
//Reveal adjascent cells.
if (grid[x][y].num_adjascent_mines == 0)
{
for (int i = x-1; i <= x+1; i++)
{
for (int j = y-1; j <= y+1; j++)
{
if (i==x && j==y) continue; //Skip the current cell.
reveal_cell(i,j);
}
}
}
}
|
Notes about the code:
-
grid
is a global structure representing each cell on the grid. I think the elements of it that I use in this function are self-explanatory and are initialized elsewhere.
-I understand that making
grid
a structure (not a class) and global is probably not the best way, but I'm not great yet and I'll get to that later.
-I do some limiting to ensure that the function does not go off of the edge of the grid. That is not relevant to this question so I have removed it to simplify what I've presented.