0

In the code snippet below the pre-increment operator used in the main function results in values starting from 2 while the post increment values start from 1 when inserting to the list. I am unable to figure out why.

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

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

void insert_node(int new_data, Node **head_ref) {
    Node *node= (Node *)malloc(sizeof (Node));
    node->data = new_data;
    node->next = *head_ref;
    *head_ref = node;
}

void display(Node *head) {
    Node *traverse = head;
    while (traverse->next != NULL) {
        printf("\ndata=%d", traverse->data);
        traverse = traverse->next;
    }
}

void main() {
    Node *pdata;
    Node *list_head = NULL;
    int i = 0;
    while (i <= 10)
        insert_node(++i, &list_head);
    display(list_head);
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189
Mukul Mehra
  • 91
  • 1
  • 9
  • These are two different operators and they work differently. Do you know what *pre* and *post* mean in their context? – Eugene Sh. Feb 02 '22 at 14:53
  • pre increments the value and then uses it. post would use the value and then increment it . Is there anything else that I am missing here ? – Mukul Mehra Feb 02 '22 at 15:02
  • 1
    Yes: in `display()` the `while (traverse->next!=NULL)` skips the last node of the list (the first once created). It has a `NULL` pointer, but valid data. – Weather Vane Feb 02 '22 at 15:06

1 Answers1

1

First, you need to understand how pre and post increment work.

Pre-Increment: increment the value of a variable before using it in an expression.

Example:

int i = 0;

// first increment value of i by 1 and then print it
print("%d", ++i); // output: 1
print("%d", i);   // output: 1

Post-Increment: increment the value of the variable after executing the expression completely, in which post-increment is used.

Example:

int i = 0;

// first use the value of i in print() and after executing
// the print(), increment value of i
print("%d", i++); // output: 0
print("%d", i);   // output: 1

Now it depends on you which one you have to use.

Second, as far as I understand there is a logical error in this function

void display(Node* head)
{
    Node* traverse = head;
    while (traverse->next != NULL)
    {
        printf("\ndata=%d", traverse->data);
        traverse = traverse->next;
    }
}

The while loop condition should be

while (traverse != NULL)

I hope, it will answer your question.

chqrlie
  • 131,814
  • 10
  • 121
  • 189
Farhan Ali
  • 116
  • 5