When is the structure (user defined data type) created?

Viewed 115

for example consider:

struct strct
{
 data member_1;
 data member_2;
 ......
};

when does the compiler recognize

struct strct 

as a data type? Is it after executing the line

struct strct

? Or after encountering the closing brace of the structure definition?

2 Answers

Declarations aren't "executed".

After reading

struct strct {

the compiler recognizes struct strct as an incomplete type, which is a type it doesn't know the size of. As you can use pointers to incomplete types, this enables you to write something like this:

struct strct {
    struct strct *next; // <- allowed, a pointer doesn't need the size of the object pointed to
    int foo;
};

Once the "body" of the struct declaration is finished, struct strct is a complete type, so you can declare variables of that type (the size must be known for that).


Side note: you could actually stop after the tag with your declaration like this:

struct strct;

and, as a consequence, have the compiler know an incomplete type struct strct. This is also called a forward declaration. Of course, it only makes sense when you have the complete declaration somewhere (possibly private in a module) as well. This is used for information hiding when implementing OOP code in C. You'd for example just declare something like this publicly:

struct strct;

struct strct *strct_create(void);
strct_foo(struct strct *self);
strct_bar(struct strct *self, int x);
[...]

and have the full declaration of struct strct in the file implementing these functions

The name struct strct is viewable as soon as it appears in the code. That allows you to create pointers to the struct as members of the struct as follows:

struct mystruct {
    int val;
    struct mystruct *next;
};

At the point the next member is defined, struct mystruct is considered incomplete. This is fine however since a pointer to an incomplete type is allowed.

Once the closing brace for the struct is encountered, the struct is considered complete and you can define instances of it.

If on the other hand you attempted to do this:

struct mystruct {
    int val;
    struct mystruct next;
};

That would be invalid since a struct cannot contain itself.

You can also create a forward declaration of a struct like this:

struct mystruct;

This also creates an incomplete type, and can allow you to have two structs that reference each other:

struct mystruct1;

struct mystruct2 {
    int val;
    struct mystruct1 *other;
};

struct mystruct1 {
    int val;
    struct mystruct2 *other;
};
Related