Typedef inside a C struct

2019-04-30 15:39发布

问题:

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?

回答1:

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



回答2:

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.



回答3:

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



标签: c struct typedef