Question

I am doing this assignment, and there are some stuff (from start-up materials) that I cannot comprehend.

typedef enum
{
    NORTH,
    EAST,
    SOUTH,
    WEST,
    NUM_POINTS
} Point;

typedef Point Course[NUM_POINTS] ;

I don't get the idea behind the last line , and how can I use it in the code?

Was it helpful?

Solution

typedef a b;

Makes b an alias for type a, e.g.

typedef int foo;

int bar;
foo bar;

both bars are equivalent. In your case,

typedef Point Course[NUM_POINTS] ;

Makes Course an alias for type Point[NUM_POINTS] (where NUM_POINTS == 4), so

Course baz;
Point baz[NUM_POINTS];

are equivalent.

OTHER TIPS

Since NUM_POINTS is the last entry in the enum, it has the highest value, and is the count of the other values. If NUM_POINTS is not meant to be used as an actual value for a Point, it looks like the purpose of the last line is to create a type name for an array of points of size equal to the number of "real" points.

Here's one nice feature: if you add more values to the enum (like NORTH_EAST, SOUTH_WEST, etc.) before NUM_POINTS, the typedef line will automatically still be correct, because the value of NUM_POINTS will have grown because of the new values inserted before it.

an enum starts at 0 and increases by 1 for each value.

So you have: NORTH = 0, EAST = 1, SOUTH = 1, WEST = 3, NUM_POINTS = 4

NUM_POINTS is set to the number of items in the enum.

The last line creates an alias of Course for a point array with 4 elements in it. The syntax is a little confusing because the array subscript is after Course and not next to Point.

typedef Point Course[NUM_POINTS] ;

However it does work the same way as for example:

int x[10];  

The [10] part is next to the variable name not the type.

It means that Course can be used to represent an array of Points, with NUM_POINTS being the number of items in the array.

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