forward referencing a structure

T

Tagore

Hi,
Following code is showing "error: field 'c' has incomplete type"
on compiling
struct a
{
struct b c;
};
struct b
{
int v;
};

but following code is fine

struct a
{
struct b *c; // pointer to b
};
struct b
{
int v;
};

Why such different behaviors shown by above codes?

Thanks,
 
E

Eric Sosman

Hi,
Following code is showing "error: field 'c' has incomplete type"
on compiling
struct a
{
struct b c;
};
struct b
{
int v;
};

but following code is fine

struct a
{
struct b *c; // pointer to b
};
struct b
{
int v;
};

Why such different behaviors shown by above codes?

C is translated "from start to finish," or in "one pass."
The meaning of almost every construct in C can depend on what
has come before it, but not by what is yet to come and has not
yet been seen.

When the compiler is processing the `struct a' definition, it
has not yet seen any definition of `struct b', and doesn't yet know
what a `struct b' looks like, how big it is, or anything about it.
So it can't put an actual `struct b' instance inside the `struct a'
that it's working on.

In the second case, though, you're not asking the compiler to
reserve space for the as-yet-undefined `struct b', but only for a
pointer to a struct of that mysterious type. The compiler doesn't
know how big a `struct b' is, but it *does* know how big a pointer
is, so it can set aside the appropriate four bytes or eight bytes
or whatever. Later, perhaps, it will find out more about `struct b',
but it can create a pointer to one without knowing all the details.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,954
Messages
2,570,116
Members
46,704
Latest member
BernadineF

Latest Threads

Top