Search code examples
cwhile-looplinked-listand-operator

Unusual characteristics of && operator in while loop in linked list deletion in C


I have been playing around with linked list and got to know some unusual characteristics of While loop with AND operatoin(I guess so).

Here what it is:

This is my delet function.I am searching for the key to be deleted.

void delet(Mynode** head,int value) {
    printf(" deleting... %d\n",value);
    Mynode *temp = *head,*prev;
    if(temp->val == value) { 
        *head = (*head)->next;
        free(temp);
        return;
    } else {
        while( temp->val != value && temp != NULL) {
            prev = temp;
            temp=temp->next;
        }
    }
    if(temp == NULL) {
        printf("..and %d is not in the list\n",value );
    } else{
        prev->next = temp->next;
    }
}

In while loop I have been checking the condition like this. and worked properly only for the value in the list.

If the value to be deleted is not in the list then it would throw a segmentation fault.

while( temp->val != value && temp != NULL) {
    prev = temp;
    temp=temp->next;
}

But interesting thing is if I swap the conditions in the while loop it works properly without any error. that is:

    while( temp != NULL && temp->val != value)

I guess swapping the conditions in while loop should't affect the output.

Could any body tell me why is that or am I going wrong all the time.

thank you for your time.


Solution

  • The condition

    temp->val != value && temp != NULL
    

    Requires temp to be not null for temp->val to work. The first bit being tested. If temp is null it will crash.

    Therefore first test if temp is not null, then look into the contents pointed to by temp.

    i.e.

    temp != NULL && temp->val != value
    

    ps: && is a short circuit operator where as soon as it knows the answer it stops evaluation