Why does forward declaration of struct not work

cforward-declarationstruct

I wrote a small code in C in which two struct types were defined which have members of each other in their definition. Case 1: If the struct foo is defined before struct bar, the code is compiled as expected. Case 2: If struct foo is defined after struct bar it will not compile which is also expected as there is no way to know the memory requirement of a struct foo variable. But I was expecting it will compile if a forward declaration of struct foo is used in case 2. But it does not work. What am I missing?

#include<stdio.h>
#include<stdlib.h>

struct foo; // forward declaration

struct bar
{
  int a;
  struct bar *next;
  struct foo ch;
};

struct foo
{
  struct bar *n;
  struct foo *nx;
};


int main()
{
  struct bar p;
  return(0);
}

Best Answer

forward declaration only informs the compiler that there is something that is called foo it does nothing says about size. you can use foo* since this is a pointer of known size but not foo itself because the size is unknwon, so the compiler does not know how the memory layout of barshould look like.

And the compiler only do a single pass through your document. so it cannot know the strucutre that is defined ahead.