I am trying to go find the next part of the linked list that is XML_ELEMENT_NODE
and stop when its found or I reach the end of the list:
do
{
cur = cur->next;
} while (cur->type != XML_ELEMENT_NODE && cur != NULL);
So I get thenext
first, because if I check first I would be stuck with the same part and would not progress. Problem is when I reached the end cur == NULL
, I can not check the type because I am at NULL
and can't get the type obviously. Is there an elegant solution for that, because all I can think of requires substitution variables that I set in the loop so I can check them in while()
. And break
is not an option I think.
You should folow a certain flow of iterations. In general, you must never dereference a null pointer, so you always have to ensure curr
is not a null pointer (briefly: curr != NULL
).
If, for any reason, you need to get the next element first, you should use:
while ( curr != NULL ) {
curr = curr->next;
if ( (curr != NULL) && (curr->type == XML_ELEMENT_NODE) )
break;
}
But the better way would be always to operate on the current node (that's why you call the pointer like that). If you know curr is not NULL
(determined by the preceeding code), you can use:
// from some previous code, you have:
curr = curr->next;
... (do something unrelated, i.e. do not dereference curr if null-pointer)
while ( (curr != NULL) && (curr->type != XML_ELEMENT_NODE) ) {
curr = curr->next;
}
After any of the loops, you have to test curr != NULL
to catch the end-of-list condition before dereferencing curr
.
Note that curr
is always the current node (the one you are starting with/working on.