Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum with struct as values?

Tags:

c

enums

So I'm pretty new to C (and to programming in general), I'd like to use a struct as the values for an enum

typedef struct {
  int x;
  int y;
} point;

// here's what I'd like to do
enum directions {
  UP = point {0, 1},
  DOWN = point {0, -1},
  LEFT = point {-1, 0},
  RIGHT = point {1, 0}
}; 

So that afterwards I could use the enum to perform coordinate transformations

If you understand what I'm trying to achieve could you please explain why this doesn't work and/or what would be the correct way to do it ?

like image 461
whateverMan99 Avatar asked Aug 24 '17 11:08

whateverMan99


1 Answers

enum is only used for translating "magic numbers" into something textual and meaningful. They can only be used for integers.

Your example is something more complex than that. It would seem that what you are really looking for is a struct, containing 4 different point members. Possibly const qualified. Example:

typedef struct {
  int x;
  int y;
} point;

typedef struct {
  point UP;
  point DOWN;
  point LEFT;
  point RIGHT;
} directions; 

...

{
  const directions dir = 
  {
    .UP    = (point) {0, 1},
    .DOWN  = (point) {0, -1},
    .LEFT  = (point) {-1, 0},
    .RIGHT = (point) {1, 0}
  };
  ...
}
like image 144
Lundin Avatar answered Oct 17 '22 07:10

Lundin