In this blog we we will learn “use of typedef in defining structure In C programming+”.  So let us write a very simple linked list data structure program without typedef and review the code. 

#include<stdio.h>
#include<malloc.h>

struct list
{
        int data;
        struct list* next;
};

void append(struct list **head, int id);
struct list* create_node(int data);

void reverse_list(struct list* curr)
{
    // Base case
    if (curr == NULL) return;
    reverse_list(curr->next);
    printf("%d ", curr->data);
}

int main()
{
    struct list *head = NULL;
    //insert 0 ,1 and 2
    int i;
    for (i = 0; i < 3; i++)
    {
        append(&head, i);
    }
    reverse_list(head);
    printf("\n");
    return 0;
}
void append(struct list **head, int data)
{
    struct list *current = *head;
    // if the list is first node
    if (current == NULL)
    {
        current = create_node(data);
        (*head) = current;
        return;
    }
    // go to last node
    while (current->next != NULL)
        current = current->next;
    struct list* new_node = create_node(data);
    current->next = new_node;
}

struct list* create_node(int data)
{
    struct list* node = (struct list*) malloc(sizeof(struct list));
    node->data = data;
    node->next = NULL;
    return node;
}

 

Note: We can see in the code that whenever we need to declare an instance of list structure, we have to prefix struct keyword before list variable. And this way there are so many structs in the above code. we can use “typedef” keyword to avoid so many structs.

Use of typedef in defining structure In C

Now let us use “typedef”keyword in the above code.

#include<stdio.h>
#include<malloc.h>

typedef struct list_
{
        int data;
        struct list* next;
} list;

void append(list **head, int id);
list* create_node(int data);

void reverse_list(list* curr)
{
    // Base case
    if (curr == NULL) return;
    reverse_list(curr->next);
    printf("%d ", curr->data);
}

int main()
{
    list *head = NULL;
    //insert 0 ,1 and 2
    int i;
    for (i = 0; i < 3; i++)
    {
        append(&head, i);
    }
    reverse_list(head);
    printf("\n");
    return 0;
}
void append(list **head, int data)
{
    list *current = *head;
    // if the list is first node
    if (current == NULL)
    {
        current = create_node(data);
        (*head) = current;
        return;
    }
    // go to last node
    while (current->next != NULL)
        current = current->next;
    list* new_node = create_node(data);
    current->next = new_node;
}

list* create_node(int data)
{
    list* node = (list*) malloc(sizeof(list));
    node->data = data;
    node->next = NULL;
    return node;
}

 

In this way by the use of keyword “typedef”, we can avoid typing so many structs in our code. It also makes our code cleaner.



Related Contents to follow