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?
In C language every declaration inside
struct
must declare a data field (possibly unnamed). That means that it is possible to define types inside astruct
in C, as long as the new type declaration is embedded as a part of a data field declaration. For exampleIn the above example type
struct Inner
is declared inside typestruct Outer
. However, the "nested"struct Inner
type declaration is not in any way localized insidestruct Outer
. It will still have file scope, since C language has no such thing asstruct
scope. This means that you can still usestruct Inner
as a member of the same file scopeMeanwhile, this trick is not applicable to
typedef
declarations, sincetypedef
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 nameMojInt
with file scope. I.e. it would behave exactly the same as if you placed yourtypedef
declaration before thestruct
.It's just not allowed. Something similar is allowed in C++ classes, but not in standard C.
Didn't know it was allowed in C++, but I can tell for certain that I have seen no vanilla C compiler accept that construct.
Here is a browsable C99 grammar that may hopefully clear up confusions: http://slps.github.io/zoo/c/iso-9899-tc3.html
Check the 1998 C++ grammar for comparison: http://slps.github.io/zoo/cpp/iso-14882-1998.html