3

I am reading The C Programming Language, and when it gets to Character Pointers and Functions (5.5) I get a problem.

In 5.5, the authors showed four versions of strcpy(). My problem lies in the version 3:

/*strcpy: copy t to s; pointer version 3*/
void strcpy(char *s, char *t)
{
    while (*s++ = *t++)
        ;
}

There is no comparison against '\0'. And how does the termination of the loop work under such a condition?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
1MinLeft
  • 93
  • 7

3 Answers3

4
*s++ = *t++

is equivalent to

(*s++ = *t++) != 0

which is equivalent to

(*s++ = *t++) != '\0'
lost_in_the_source
  • 10,998
  • 9
  • 46
  • 75
3

There is. The value of the assignment statement is the value assigned. So it will be checking whether the assigned value is 0 ('\0') or not which is what is expected to be done over here.

Equivalently this code boils down to (this is how it would work). Think like this - atleast once the copy will happen. So it shows us that it will be a do-while loop.

char somechar;
do {
   somechar = *t;
   *s = somechar ;
   s++;
   t++;
} while( somechar );
user2736738
  • 30,591
  • 5
  • 42
  • 56
1

In C, if (var = expression) means 1) assign expression to var, then 2) check if var evaluates to TRUE. The same is for while (var = expression).