views:

157

answers:

4

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?

+3  A: 

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.

Brian R. Bondy
I know that, I just don't get how or why would we use the last line.I feel like I should explain more, should I :) ?
m4design
Well, the number of items you are intended to *use*. Not an uncommon idiom, and very slick when its a good idea.
dmckee
@M4design: Was still writing as you wrote that, please recheck might make more sense now.
Brian R. Bondy
+3  A: 
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.

KennyTM
I kinda got your point.So what does Point[4] exactly mean?If Point was a structure then I would get, but it's an 'enum'.Excuse my ignorance.
m4design
An enum is just an int under the covers. So it's making you an array of integers.
Vicky
@M4design: An array of 4 `Point`'s. You could think an `enum` as an `int`.
KennyTM
A: 

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

Andrew
+3  A: 

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.

Bkkbrad