Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - Logical AND operands not swapable in this case?

Tags:

c

I am learning linked lists in C, and I came across an error I don't understand. In the snippet of code I have pasted below, when I have while(a && b), I get an infinite loop, but when I run while(b && a), the program works. I am new to C and don't understand why I get the infinite loop in the first case.

This gives me an infinite loop:

while((*searchNodePtr).data != dataValue && searchNodePtr != NULL) {
    prevNodePtr = searchNodePtr;
    searchNodePtr = (*searchNodePtr).next;  
}

But this works (swapped while condition operands):

while(searchNodePtr != NULL && (*searchNodePtr).data != dataValue) {
    prevNodePtr = searchNodePtr;
    searchNodePtr = (*searchNodePtr).next;  
}

Any clarification would be much appreciated. Thank you.

like image 461
user3016362 Avatar asked Feb 09 '23 07:02

user3016362


1 Answers

This is due to short-circuit evaluation. In the first while you dereference a NULL-pointer (undefined behaviour) when searchNodePtr is NULL because the check for NULL only happens after that.

Whereas in the second while when the first operand of the && is false, the second doesn't get evaluated. So when searchNodePtr is NULL the expression (*searchNodePtr).data is not evaluated and you don't dereference the NULL-pointer.

like image 108
Kninnug Avatar answered Feb 11 '23 21:02

Kninnug