c++ For loop - "Error: Expected a declaration"

e3bfsja2  于 2022-12-15  发布在  其他
关注(0)|答案(4)|浏览(142)

As part of a text-based Battle Ship game, I'm trying to make a simple grid/board appear in the console. Unfortunately I'm having errors just making the grid. The grid is represented by a 2D array, -I'm using a for loop to initially set each element of the grid to "EMPTY". When I try to get the code running, however, I get an error saying "Expected a declaration" and "syntax error : ')' ". What am I doing wrong? Here's the portion of code in question:

enum GridContent {SHIP, HIT, MISS, EMPTY};

const int GRID_SIZE = 10;

GridContent board[GRID_SIZE][GRID_SIZE];

// Intellisense error on "for": "Expected a declaration."
for (int y = 0; y < GRID_SIZE; y++)
/* Errors for above line: "Missing ';' before '++', '<', '{', and ')'",
"Syntax error: ')'", "Syntax error: 'for'", "'int y' : redefinition"" */
{ // "Missing ';' before '{'"
    for (int x = 0; x < GRID_SIZE; x++)
        board[y][x] = EMPTY;
}
r1wp621o

r1wp621o1#

你必须用GridContent替换Grid,我想是在Grid board[GRID_SIZE][GRID_SIZE]行中;

laik7k3q

laik7k3q2#

I think that you mean

for (int x = 0; x < GRID_SIZE; x++)
    board[y][x] = EMPTY;

instead of

for (int x = 0; x < GRID_SIZE; x++)
    grid[GRID_SIZE][GRID_SIZE] = EMPTY;

In your code snippet grid is an undeclared identifier and .using value GRID_SIZE as an index is wrong because the corresponding element will be beyond the array.
Also from your code snippet it is not clear whether the array has to be defined like

Grid board[GRID_SIZE][GRID_SIZE];

or like

GridContent board[GRID_SIZE][GRID_SIZE];
pnwntuvh

pnwntuvh3#

数组名是board,Grid是some类型。1.所以在循环的i侧,你应该使用board而不是grid。2.你的数组是GRID_SIZE,当你访问时,你已经使用了那个变量,它意味着arrayIndexOutOfBound

5m1hhzi4

5m1hhzi44#

Related to Vlad from Moscow's comment about namespaces: I've had a similar issue and it was because I hadn't included my code with a main block.
ie. The following gets all the errors mentioned:

for (int y = 0; y < GRID_SIZE; y++)
    {
        for (int x = 0; x < GRID_SIZE; x++)
        board[y][x] = EMPTY;
}

But this works fine:

int main()
{
    for (int y = 0; y < GRID_SIZE; y++)
    {
        for (int x = 0; x < GRID_SIZE; x++)
            board[y][x] = EMPTY;
    }
}

相关问题