In the below code a pointer (ptr
) is used as the condition of a while loop. Can you tell me how that loop is working?
struct Node* ptr = head;
while (ptr)
{
printf("%d -> ", ptr->data);
ptr = ptr->next;
}
printf("null\n");
CodePudding user response:
In c there is no boolean type but Zero is interpreted as false and anything non-zero is interpreted as true.
for example this if body will be executed
if (3) { printf("true"); }
also in C NULL
is a constants with value 0 as (void *)
type
so in your loop any if ptr
is null the condition will be like while (0)
so it will stop the loop
You loop will check the current node if it null it will stop, else it will point to the next node
Check this useful answer also for more information: What is the difference between NULL, '\0' and 0?