Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are pointers to incomplete types allowed and not variables of incomplete types?

Why is the following legal:

typedef struct a aType;
struct a
{
   int x;
   aType *b;
};

and the following illegal:

void main()
{
    typedef struct a aType;
    aType someVariable;
    struct a
    {
      int x;
      aType *b;
    };
}

I'm just curious as in each case it is forward referencing and as far as I know, at least for functions and variables, forward referencing is not legal.

Also, would the answer for this be the same for C++ as well?

like image 380
Anurag Avatar asked Nov 26 '25 14:11

Anurag


2 Answers

You are allowed to create pointers to incomplete types, because the size of the pointer object does not depend on the size of the pointed-to type. Pointers to different struct types have the same size and representation, regardless of the size of the struct type itself.

You are not allowed to create instances of incomplete types, since the size of the type isn't known.

like image 185
John Bode Avatar answered Nov 28 '25 03:11

John Bode


This of it this way:

typedef struct a aType;
struct a { int x; aType *b; };

is the same as:

struct a;
typedef struct a aType;
struct a { int x; aType *b; };

So you're forward-declaring a struct, typedefing it and later defining it. Perfectly fine.

Now the second example:

typedef struct a aType;
aType someVariable;
struct a { int x; aType *b; };

This has nothing to do with the fact that it's in local scope. What's happening is this:

struct a;
typedef struct a aType;
aType someVariable; // error: when it gets here, aType is still incomplete
struct a { int x; aType *b; };
aType someVariable; // perfectly fine, aType not incomplete

Remember that compilation happens in order. When you try to declare someVariable the compiler doesn't know what struct a is yet, so it doesn't know its size, hence it doesn't know how much memory to allocate for it, hence a compile error. Declaring it after aType is defined works as expected.

like image 39
DeiDei Avatar answered Nov 28 '25 04:11

DeiDei



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!