Reputation: 19
I wrote a program for linked list which accepts value in ascending order. I have a while loop inside the program regarding which I have a question. I'm not entering the full code, it's just the modular function for inserting in ascending order. Here, x is taken as input from user and head node is passed into the function. Now, In while loop, if I exchange the conditions, i.e. keep "x > temp->next->data" in front and move "temp->next != NULL" behind, then, I'm getting an error if my input sequence is like (1, 2, 3, 4, 5) i.e. already in ascending order.
list *insert(list *head, int x)
{
list *temp = head, *prev = temp, *temp2 = create();
temp2->data = x;
if(head == NULL || x < head->data)
{
temp2->next = head;
head = temp2;
}
else
{
while(temp->next != NULL && x > temp->next->data) //while(x > temp->next->data && temp->next != NULL)
{
temp = temp->next;
}
temp2->next = temp->next;
temp->next = temp2;
}
return head;
}
The way I think it is, when I enter 1, it goes to if statement(considering head is empty initially) and 1 is added to list. Then, when I enter 2 and if it checks the condition, temp->next is NULL due to only one element in list, and, NULL->data will give an error. But, it works if the conditions are according to the program above. Is it that while loop gives precedence to the conditions within itself?
Upvotes: 0
Views: 334
Reputation: 224417
The behavior you're seeing is not related specifically to while
but to the logical AND operator &&
.
The &&
operator is a "short-circuit" operator. This means that if the result of the operand can be determined solely by evaluating the left operand, then the right operand is not evaluated at all.
In this specific case that's a good thing. In the event that temp->next
is NULL, the left operand of &&
is false so we know that the result of the operator is false and therefore it is not necessary to evaluate x > temp->next->data
If however you were to switch the operands of &&
:
x > temp->next->data && temp->next != NULL
Then temp->next->data
gets evaluated without checking if temp-next
is NULL. This opens up the possibility of dereferencing a NULL pointer which invokes undefined behavior.
Upvotes: 1