Search code examples
gccstructdeclare

Undefined struct name can be used to declare new struct variable


I have not define struct a, however I can declare variable with struct a. The following code can be compiled on Linux by GCC, so , what's the member of struct a ? Does a is just recognized as char * ? I don't know it's meaning.

void main() {
    struct a *a1;
    a1 = 0;
}

Solution

  • struct a *a1;
    

    declares a1 as a pointer to struct a. You can legally declare a pointer to an incomplete struct type a because the compiler does not need to know the definition of struct a to create a pointer to it. All pointers to struct types have the same memory representation and alignment requirements, and that's all the compiler needs to know to create one. Your assignment:

    a1 = 0;
    

    simply sets the pointer to 0, i.e. makes it a null pointer. It presumes nothing about the type of object that pointer might point to. If instead you were to attempt something like:

    a1->member = 0;
    

    that would require the compiler to have a definition of struct a and you would see a compilation failure like:

    main.c:3:7: error: dereferencing pointer to incomplete type ‘struct a’
         a1->member = 0;
           ^
    

    Later

    Where do I need use this syntax? Usually what does undefined struct be used for?

    The classic use of incomplete struct pointers is to implement an abstract datatype in C. The C API exposed through a header file is defined in terms of "opaque" struct pointers - pointers to incomplete types - so that the client can query and manipulate objects addressed by these pointers only via the API and cannot circumvent it to handle the objects in unapproved ways, because they cannot see the definitions of the datatypes that the opaque pointers point to! Here's an elementary example from the C FAQ