UNIX Socket FAQ

A forum for questions and answers about network programming on Linux and all other Unix-like systems

You are not logged in.

  • Index
  • » C
  • » How to declare structure before compiler can see its defination.

#1 2010-03-07 04:08 PM

santoshkumar
Member
Registered: 2007-08-21
Posts: 53

Re: How to declare structure before compiler can see its defination.

1. Is it possible to use self referential structures like below,

struct test
{
  struct test w;
  int y;
};

Is there way like forward declaration as in c++.



2. Related how to make use of forward declaration as in c++ in c.
ex abc is declared below and need to use it  before it is defined.

struct abc;  /*??*/

struct node
{
struct abc r;
int data;
};

struct abc
{
int y;
struct node y;
};

main()
{
struct node a,b;

a.data =1;
}

Offline

#2 2010-03-07 06:42 PM

RobSeace
Administrator
From: Boston, MA
Registered: 2002-06-12
Posts: 3,839
Website

Re: How to declare structure before compiler can see its defination.

Well, you can declare a POINTER to your struct from within the definition of the same
struct...  But, you can't declare another direct copy of the entire struct itself in place,
since that would be infinitely recursive, and your struct would be infinitely large!  (Ie:
your "w" would contain an element "w", which would contain an element "w", and so
on forever...)  Ie: this is fine:

struct test {
    struct test *w;
    int y;
};

But, your similar first struct without the "*" will never work...

And, you CAN pre-declare the struct like you show in the second case, by just
doing a simple "struct abc;" by itself...  But, it's generally not necessary, as long as
you use the full name of the struct with "struct" keyword, anyway...  The only time
you really need to do that is if you're making typedefs from the structs, and need
to use the typedef prior to the definition of the actual struct...  Then, you can pre-declare
the struct, make the typedef, use it, and go on to fully define the struct later...

Offline

  • Index
  • » C
  • » How to declare structure before compiler can see its defination.

Board footer

Powered by FluxBB