Search code examples
cstructcompilationdeclarationdefinition

Structure declaration and definition in C


If we write something like this:

typedef struct 
{
    unsigned int counter;
} MyStruct;

This represents structure declaration?

Declaration says our compiler that somewhere there is a structure which have parameters of type and size like above, and no space is reserved in memory for that structure in case of declaration.

and definition is, as now we reserved a space in memory for our structure:

MyStruct tmpStruct;

Or I am wrong?

Please clarify the situation with structures.


Solution

  • There are different kinds of definitions in C - type definitions, variable definitions, and function definitions. Types and functions could also be declared without being defined.

    Your typedef is not a declaration, it's a definition of a type. In addition to defining a struct with no tag, it defines a type name that corresponds to that struct.

    A declaration of a struct would look like this:

    typedef struct MyStruct MyStruct;
    

    This would let you declare pointers to MyStruct, forward-declare functions that take MyStruct*, and so on:

    void foo(MyStruct* p);
    

    What you have is a declaration/definition of a variable of type MyStruct:

    MyStruct tmpStruct;
    

    Here is a complete example with struct's declaration separated from its definition:

    #include <stdio.h>
    // Here is a declaration
    typedef struct MyStruct MyStruct;
    // A declaration lets us reference MyStruct's by pointer:
    void foo(MyStruct* s);
    // Here is the definition
    struct MyStruct {
        int a;
        int b;
    };
    // Definition lets us use struct's members
    void foo(MyStruct *p) {
        printf("%d %d\n", p->a, p->b);
    }
    
    int main(void) {
        // This declares a variable of type MyStruct
        MyStruct ms = {a:100, b:120};
        foo(&ms);
        return 0;
    }
    

    Demo.