Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

About "NULL" in this specific code

Tags:

c

I bought this book called "Writing Solid Code".

In the first chapter, there's this code:

while(*pchTo++ = *pchFrom++)
   NULL;

I really don't get what that NULL does in that loop.

like image 537
ksp0422 Avatar asked May 06 '13 14:05

ksp0422


2 Answers

The author could have written an entirely empty while loop just like you can write a body-less for loop. That would have looked like:

while (*pchTo++ = *pchFrom++);

/* or */

while (*pchTo++ = *pchFrom++)
    ;

Both of which might look confusing for some people so they added the NULL to give it a body and make it less confusing.

Edit

Note you can do the same with a for loop:

for (head = list->head; head->next; head = head->next);
/* or */
for (head = list->head; head->next; head = head->next)
    ;
/* or */
for (head = list->head; head->next; head = head->next)
    NULL;

And all that will do is traverse a list by going to the next element while the next element is not NULL

like image 180
Ian Stapleton Cordasco Avatar answered Oct 05 '22 16:10

Ian Stapleton Cordasco


That loop copies a string. The NULL is just there to provide a loop body.

like image 27
austin Avatar answered Oct 05 '22 15:10

austin