-2
struct A { 
    struct B b;
};
struct B {
    struct A a;
};
  • Please explain these structure declarations — are they valid?
  • Is there any application for such declarations — if so, can you give an example?
  • Are these self-referential structures?
Mohit Jain
  • 30,259
  • 8
  • 73
  • 100
harish n
  • 21
  • 2

1 Answers1

5

It is invalid and not needed in procedural language like C. (May be useful in languages which do lazy evaluation for ex: Haskell).

Imagine a use case of your example

struct A { 
  struct B b;
};
struct B {
  struct A a;
};
Struct A a;
a.b.a.b.a.b.......[infinitely]

But yes sometimes you need to refer structures of type A and B into each other, in that case you can use pointers.

struct child;
struct parent;

struct child { 
  ...
  struct parent *pParent;
};

struct parent {
  ...
  struct child *children[2];
};

Now the possible use case would be:

struct child pikachu;
...
if(pikachu.pParent != NULL) {
  struct child *pPikachuSibling;
  pPikachuSibling = (pikachu.pParent.children[0] == &pikachu) ?
                           pikachu.pParent.children[1] :
                           pikachu.pParent.children[0];
  if(pPikachuSibling != NULL) {
    do_something_with(pPikachuSibling);
  }
}

In C a field can not have incomplete type[a], but field are allowed to be pointers to incomplete type.

About Self referential struct, using pointers, you can achieve this requirement.

assert( pikachu.pParent.children[0] == &pikachu) ||
        pikachu.pParent.children[1] == &pikachu) );

[a] Quoting from ISO/IEC 9899:TC2 Committee Draft — May 6, 2005 WG14/N1124

109) An incomplete type may only by used when the size of an object of that type is not needed. It is not needed, for example, when a typedef name is declared to be a specifier for a structure or union, or when a pointer to or a function returning a structure or union is being declared. (See incomplete types in 6.2.5.) The specification has to be complete before such a function is called or defined.

6.2.5 Types

22 An array type of unknown size is an incomplete type. It is completed, for an identifier of that type, by specifying the size in a later declaration (with internal or external linkage). A structure or union type of unknown content (as described in 6.7.2.3) is an incomplete type. It is completed, for all declarations of that type, by declaring the same structure or union tag with its defining content later in the same scope.

Mohit Jain
  • 30,259
  • 8
  • 73
  • 100