1

I have 2 type definitions of structs, ARRAY and OBJECT.

ARRAY has elements in in that are OBJECT. OBJECT (when it's TYPE is COMPLEX) has array of it's children

enum {
      INT,
      FLOAT,
      STRING,
      CHAR,
      COMPLEX
} typedef TYPE;

struct {
  TYPE type;
  ARRAY children;
  char name[50];
} typedef OBJECT;

struct {
  OBJECT* elements;
  int size;
} typedef ARRAY;

I want to create these structs but that's not possible because each one depends on the definition of the other. I get this error:

t.c:11:3: error: unknown type name 'ARRAY'
  ARRAY children;
  ^
1 error generated.
Ulysse BN
  • 10,116
  • 7
  • 54
  • 82
  • 2
    That's a strange syntax you have there. Not knowing about forward declarations is half of your problem. – DeiDei Mar 26 '19 at 17:04
  • @DeiDei I know what they are. I dont know how to use them here. – Evžen Křídlo Mar 26 '19 at 17:10
  • 1
    Apart from the invalid syntax, you need to declare at least your object struct with a tag so that you can forward declare it. – Ian Abbott Mar 26 '19 at 17:18
  • To better understand what you are doing with `typedef` and `struct`, I suggest reading [C : typedef struct name {…}; VS typedef struct{…} name;](https://stackoverflow.com/a/23660072/6320039) – Ulysse BN Aug 09 '21 at 21:33

1 Answers1

3

Here is one way to declare the TYPE, OBJECT and ARRAY type aliases, using a forward declaration of the OBJECT type alias to avoid circular dependencies. This requires the associated struct type to be declared with a tag that will match its later complete declaration.

typedef enum {
    INT,
    FLOAT,
    STRING,
    CHAR,
    COMPLEX
} TYPE;

// incomplete declaration of struct _OBJECT and OBJECT
typedef struct _OBJECT OBJECT;

typedef struct {
    OBJECT* elements;
    int size;
} ARRAY;

// complete declaration of struct _OBJECT
struct _OBJECT {
    TYPE type;
    ARRAY children;
    char name[50];
};
Ian Abbott
  • 15,083
  • 19
  • 33