Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!

How to initialize C structs with default values

New member
Joined
Feb 1, 2023
Messages
18
I have this defined struct:

Code:
#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?
 
New member
Joined
Feb 1, 2023
Messages
9
In C, whether an object is initialized or not depends on how you declare the object, for example whether it is 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 default values:

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

You can call this function to initialize the object, for example like this:

Code:
List list1;
init_list( &list1 );

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

Code:
List list1 = { 0, NULL, NULL };
Since everything is being initialized to zero, it is sufficient to write:

Code:
List list1 = { 0 };
 
New member
Joined
Feb 1, 2023
Messages
17
In C opposite to C++ you may not initialize data members in structure declarations like you are doing

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

Also it does not make sense to declare the global pointer list1.

Code:
List* list1;
What you need is to write

Code:
typedef struct List {
    int size;
    Node* head;
    Node* tail; // I think you mean `tail` instead of `tai`
} List;

int main( void )
{
    List list1 = { .size = 0, .head = NULL, .tail = NULL };
    //...;
 
Top