Home > Mobile >  Why is this j considered an undeclared identifier when it's declared
Why is this j considered an undeclared identifier when it's declared

Time:12-06

The j in the printing statement is considered an undeclared identifier, how do I fix this?

for (int i = 0; i < 9; i  ) {
    for (int j = 0; j < 9; j  )
        switch(grid[i][j]){
            case '.':
                colourChange(WHITE);
                break;
            case 'P':
                colourChange(YELLOW);
                break;
            case 'G':
                colourChange(PINK);
                break;
            case 'W':
                colourChange(BLUE);
                break;}
        printf("%c  ", grid[i][j]);
    printf("\n");
}

I declared it in the for loop, but it gave an error. Also if I comment out the full switch statement it works.

CodePudding user response:

The body of the inner for loop is just the switch statement, so the call to printf that follows is outside of the inner loop.

Always use braces:

for (int i = 0; i < 9; i  ) {
    for (int j = 0; j < 9; j  ) {
        switch(grid[i][j]) {
            case '.':
                colourChange(WHITE);
                break;
            case 'P':
                colourChange(YELLOW);
                break;
            case 'G':
                colourChange(PINK);
                break;
            case 'W':
                colourChange(BLUE);
                break;
        }
        printf("%c  ", grid[i][j]);
    }
    printf("\n");
}

CodePudding user response:

This is because your second for statement. Since it has no curly braces, it assumes the next statement corresponds to its body. Your following printf("%c ", grid[i][j]); assumes that there is no j to take into account and is not recognized. A fixed solution may be:

for (int i = 0; i < 9; i  ) {
    for (int j = 0; j < 9; j  ) {
        switch(grid[i][j]) {
            case '.':
                colourChange(WHITE);
                break;
            case 'P':
                colourChange(YELLOW);
                break;
            case 'G':
                colourChange(PINK);
                break;
            case 'W':
                colourChange(BLUE);
                break;
        }
        printf("%c  ", grid[i][j]);
    }
    printf("\n");
}
  •  Tags:  
  • c
  • Related