Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

Try declaring the enum as follows:

typedef enum Colors
{
  black,
  white
} my_colors;

and use my_colorsin the function. I think it might help

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top