Typedef inside a C struct

2019-04-30 14:56发布

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?

标签: c struct typedef
3条回答
姐就是有狂的资本
2楼-- · 2019-04-30 15:33

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.

查看更多
一纸荒年 Trace。
3楼-- · 2019-04-30 15:53

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

查看更多
\"骚年 ilove
4楼-- · 2019-04-30 15:55

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

查看更多
登录 后发表回答