问题
Why is the following legal:
typedef struct a aType;
struct a
{
int x;
aType *b;
};
and the following illegal:
void main()
{
typedef struct a aType;
aType someVariable;
struct a
{
int x;
aType *b;
};
}
I'm just curious as in each case it is forward referencing and as far as I know, at least for functions and variables, forward referencing is not legal.
Also, would the answer for this be the same for C++ as well?
回答1:
This of it this way:
typedef struct a aType;
struct a { int x; aType *b; };
is the same as:
struct a;
typedef struct a aType;
struct a { int x; aType *b; };
So you're forward-declaring a struct
, typedef
ing it and later defining it. Perfectly fine.
Now the second example:
typedef struct a aType;
aType someVariable;
struct a { int x; aType *b; };
This has nothing to do with the fact that it's in local scope. What's happening is this:
struct a;
typedef struct a aType;
aType someVariable; // error: when it gets here, aType is still incomplete
struct a { int x; aType *b; };
aType someVariable; // perfectly fine, aType not incomplete
Remember that compilation happens in order. When you try to declare someVariable
the compiler doesn't know what struct a
is yet, so it doesn't know its size, hence it doesn't know how much memory to allocate for it, hence a compile error. Declaring it after aType
is defined works as expected.
回答2:
You are allowed to create pointers to incomplete types, because the size of the pointer object does not depend on the size of the pointed-to type. Pointers to different struct
types have the same size and representation, regardless of the size of the struct
type itself.
You are not allowed to create instances of incomplete types, since the size of the type isn't known.
来源:https://stackoverflow.com/questions/41751479/why-are-pointers-to-incomplete-types-allowed-and-not-variables-of-incomplete-typ