문제

typedef enum Colors{black, white};
void chess(int rows, int cols, Colors array[rows][cols]) {
   for (int i = 0; i <  rows; i++) {
       for (int j = 0; j < cols; j++) {
           if (i+j % 2 == 0) {
               array[i][j] = black;
           } else {
               array[i][j] = white;
           }
       }
   }
}

I am getting an error saying error: expected declaration specifiers or ‘...’ before ‘Colors’

I have made sure I've declared the enum type correctly, so am not sure what the issue is here.

도움이 되었습니까?

해결책

An enum is normally defined as enum Colors { black, white }; and has to be referred to by the name enum Colors (the enum in front is required). For instance:

enum Colors { black, white };

void print_color(enum Colors color) {
  if(color == black) {
    printf("Black\n");
  } else if(color == white) {
    printf("White\n");
  }
}

Now, the "typedef" syntax is typedef enum { black, white } Colors;, and now we just refer to it by the name Colors (no enum in front):

typedef enum { black, white } Colors;

void print_color(Colors color) {
  if(color == black) {
    printf("Black\n");
  } else if(color == white) {
    printf("White\n");
  }
}

This weird syntax is becuase enum { black, white } is actually a nameless enum, and the typedef keyword gives this nameless type a name.

다른 팁

Try declaring the enum as follows:

typedef enum Colors
{
  black,
  white
} my_colors;

and use my_colorsin the function. I think it might help

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top