问题
If I declare a struct like this:
struct
{
int a;
char b;
} ident;
does that structure has a type? (i.e. an unspecified type, a default type, etc.).
Instead If I declare a struct like:
struct J
{
int a;
char b;
} ident;
we can say that ident
is a stucture variabile of type struct J
.
回答1:
After
struct { int a; char b; } ident;
ident
has an “anonymous structure type” and you won’t be able to declare another variable of the same type*). That is, two anonymous structure types are never compatible. If you did, for example,
struct { int a; char b; } ident2;
afterwards, ident
and ident2
would be of different (though identical) type and an assignment like
ident2 = ident;
would be a constraint violation (a compiler must give a diagnostic message and may refuse to compile, what most compilers probably will).
*) Some compilers have extensions to allow it. For example, with Gcc, you can do:
typeof(ident) ident2 = ident;
来源:https://stackoverflow.com/questions/25871851/structure-without-a-tag