Search code examples
cstructinitializationdeclaration

How to initialize C structs with default values


I have this defined struct:

#include <stdio.h>
#include <stdlib.h>

typedef struct Node {
    int data;
    struct Node* prev;
    struct Node* next;
} Node;

typedef struct List {
    int size = 0;
    Node* head = NULL;
    Node* tai = NULL;
} List;

List* list1;

For the the node one it is Ok, but for the List one I have a declaration error in visual studio (2022), I am new to C, how to declare default values in C structs?


Solution

  • In C, whether an object is initialized or not depends on how you declare the object, for example whether you declare it as an object of static storage duration (which is initialized to zero unless you explicitly initialize it to something else) or an object of automatic storage duration (which is not initialized, unless you explicitly initialize it).

    Therefore, it would not make sense to assign default values to the type definition, because even if the language allowed this, it would not guarantee that the object of that type will be initialized.

    However, you can create your own function which initializes your struct to specific values:

    void init_list( List *p )
    {
        p->size = 0;
        p->head = NULL;
        p->tail = NULL;
    }
    

    Assuming that the object is declared inside a function (not at file scope), you can use the following code to declare and initialize the object to default values:

    List list1;
    init_list( &list1 );
    

    If the object is declared at file scope, you can't call the function init_list at file scope, but you can call the function inside the function main, for example.

    Alternatively, when you declare the object, you can also initialize the individual members:

    List list1 = { 0, NULL, NULL };
    

    This will also work at file scope.

    Since everything is being initialized to zero, it is sufficient to write the following:

    List list1 = { 0 };
    

    In that case, all members that are not explicitly assigned a value will be initialized to zero.