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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With