-2

I am writing a game in C. But I keep getting a number of errors. One prominent one is this. "Illegal Identifier: X" where X is the type of a variable inside a structure. An instance, Illegal Identifier: MapItem, is caused by the following code

typedef struct MapItem{
int item;
int count;
};

typedef struct MapTile{
MapItem item;
int x;
int y;
int tile;
Direction dir;
int drop;
};

The error is attached to the first line inside the MapTile struct. I would like to know why this error is occurring, and how to fix it.

The code segment was taken, in exact order, from map.h. Direction is an enum declared earlier in the same header.

Thank you all for answering. However, I did receive the answer I needed 4 hours ago.

2 Answers2

1

Your typedef are incorrect. The syntax is:

typedef type typealias ;

So:

typedef struct 
{
    int item;
    int count;
} MapItem;

typedef struct
{
    MapItem item;
    int x;
    int y;
    int tile;
    Direction dir;
    int drop;
} MapTile;

Note that types being aliased here are anonymous structs, the struct-tag is only required for self-referencing structs.

Clifford
  • 88,407
  • 13
  • 85
  • 165
1

typedef is used to create an alias to another type (existing or defined in the same typedef statement).

Its general format is:

typedef existing_or_new_type alias;

The aliased type in your typedef is the new struct MapItem defined in the typedef statement but the alias is missing. This is the cause of the error.

You can use:

typedef struct MapItem {
    int item;
    int count;
} MapItem;

This statement declares the new type struct MapItem (the struct keyword is part of the type name) and the new type MapItem that is an alias of struct MapItem. This means that everywhere you can or have to use struct MapItem you can use MapItem instead.

If this seems confusing, you can use different names for the struct type and its alias. Or you can omit the name from the struct definition at all:

typedef struct {
    int item;
    int count;
} MapItem;

This way, MapItem is the name of an anonymous struct type and it is the only way to declare variables of this type.

axiac
  • 68,258
  • 9
  • 99
  • 134