Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typedef inside a C struct

Tags:

c

struct

typedef

First off the code which boggles my mind:

typedef struct Object {
    typedef int MyInt;
    void (*destructor)(Object *);
    void *(*constructor)(struct Object *);
} Object;

Why does the compiler prevent me from defining a typedef inside a struct?

like image 602
mic4ael Avatar asked Dec 02 '13 19:12

mic4ael


2 Answers

In C language every declaration inside struct must declare a data field (possibly unnamed). That means that it is possible to define types inside a struct in C, as long as the new type declaration is embedded as a part of a data field declaration. For example

struct Outer {
  struct Inner {
    int i;
  } field;
};

struct Outer a;
a.field.i = 42;

In the above example type struct Inner is declared inside type struct Outer. However, the "nested" struct Inner type declaration is not in any way localized inside struct Outer. It will still have file scope, since C language has no such thing as struct scope. This means that you can still use struct Inner as a member of the same file scope

struct Inner b;
b.i = 42;

Meanwhile, this trick is not applicable to typedef declarations, since typedef declarations do not declare data fields.

Note that in the spirit of C language, even if your typedef declaration was somehow legal, it would still declare a typedef name MojInt with file scope. I.e. it would behave exactly the same as if you placed your typedef declaration before the struct.

like image 139
AnT Avatar answered Oct 20 '22 03:10

AnT


It's just not allowed. Something similar is allowed in C++ classes, but not in standard C.

like image 21
Guido Avatar answered Oct 20 '22 02:10

Guido