This is bizarre. I haven't read anywhere that defining a structure inside another structure definition allowed in C. But this link says its allowed.
http://www.c4learn.com/structure-within-structure-nested.html
Is this true?
This is bizarre. I haven't read anywhere that defining a structure inside another structure definition allowed in C. But this link says its allowed.
http://www.c4learn.com/structure-within-structure-nested.html
Is this true?
Yes, you can declare nested structure. Here is the syntax:
C11 (n1570), § 6.7.2.1 Structure and union specifiers
struct-or-union-specifier: struct-or-union identifier (opt) { struct-declaration-list } struct-or-union identifier struct-declaration-list: struct-declaration struct-declaration-list struct-declaration
Inception! We must go deeper!!
struct EvenDeeper {
int a, b, c;
struct {
char a;
} u;
};
struct Inner {
struct EvenDeeper e;
};
struct Outer {
struct Inner i;
};
int main(int argc, char *argv[]) {
struct Outer o;
o.i.e.a = 5;
o.i.e.b = 4;
o.i.e.c = 3;
o.i.e.u.a = '?';
printf("%d:%d:%d:%c", o.i.e.a, o.i.e.b, o.i.e.c, o.i.e.u.a);
return 0;
}
Compiles properly with "gcc -std=c89" with output:
5:4:3:?
Struct structure defined in §6.7.2.1
Yes, you can declare a structure within another structure.
The two downsides I see are:
1. Readability: it might make your code hard for others to read, especially if it's in a team project.
2. The inner structure's will be scoped only to the outer structure, not to mention that(depending on how it's defined), it can only be used once and reusing the same structure will require re-defining it again.
Hope this helps.