I have a program that defines a typedef struct within an existing typedef struct, and I am wondering why I am getting a compilation error.
Here is the program:
typedef struct Outer
{
typedef struct Inner
{
int b;
}INNER;
INNER inner;
int a;
}OUTER;
int main()
{
OUTER obj;
obj.a = 10;
obj.inner.b=8;
return 0;
}
on compilation gives following error ::
test.c:3:5: error:expected specifier-qualifier-list before ‘typedef’
test.c: In function ‘main’:
test.c:17:5: error: ‘OUTER’ has no member named ‘a’
test.c:18:5: error: ‘OUTER’ has no member named ‘inner’
but, when I changed the program to
typedef struct Outer
{
struct Inner
{
int b;
};
struct Inner inner;
int a;
}OUTER;
int main()
{
OUTER obj;
obj.a = 10;
obj.inner.b=8;
return 0;
}
it compiles successfully.
Why is typedef not allowed with inner structures?
C does not allow a storage-class specifier (
typedef, but alsostaticorextern) in the declaration of a structure member. This is specified in the syntax of structures and unions declaration in 6.7.2.1p1 in C99.You can compare 6.7.2.1p1 syntax with the syntax of a declaration where the declarator is not a function parameter or a structure / union member in 6.7p1 and see that in this case the storage-class specifiers are allowed.