0

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");
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
  • 4
    The loop will continue until ptr is null. – ddastrodd Jul 18 '22 at 05:07
  • It just keeps looping until the `ptr` is NULL. Starts off with the `head` pointer as current and moves to the `next` pointer on each iteration until the current pointer is NULL. In C, NULL is 0 and 0 is false. – kaylum Jul 18 '22 at 05:07
  • It basically checks every time whether that pointer points to something and not NULL. If it does, it executes the while loop code. – kiner_shah Jul 18 '22 at 05:08
  • This is a very standard walk of a linked list (whether singly or doubly linked doesn't matter). You _might) more often see this with a for loop (especially in C++ where the initializer can be a full declarative statement) but it still works fine. – SoronelHaetir Jul 18 '22 at 05:12
  • A pointer is just a number. – Schwern Jul 18 '22 at 07:27

1 Answers1

1

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?

AmrDeveloper
  • 3,826
  • 1
  • 21
  • 30