How does "while(*s++ = *t++)" copy a string?

It is equivalent to this:

while (*t) {
    *s = *t;
    s++;
    t++;
}
*s = *t;

When the char that t points to is '\0', the while loop will terminate. Until then, it will copy the char that t is pointing to to the char that s is pointing to, then increment s and t to point to the next char in their arrays.


This has so much going on under the covers:

while (*s++ = *t++);

The s and t variables are pointers (almost certainly characters), s being the destination. The following steps illustrate what's happening:

  • the contents of t (*t) are copied to s (*s), one character.
  • s and t are both incremented (++).
  • the assignment (copy) returns the character that was copied (to the while).
  • the while continues until that character is zero (end of string in C).

Effectively, it's:

while (*t != 0) {
    *s = *t;
    s++;
    t++;
}
*s = *t;
s++;
t++;

but written out in a much more compact way.