Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

My question is, what does this code do (from http://www.joelonsoftware.com/articles/CollegeAdvice.html):

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

the website says that the code above copies a string but I don't understand why...

does it have to do with pointers?

like image 578
Devoted Avatar asked May 01 '09 04:05

Devoted


2 Answers

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.

like image 111
Paige Ruten Avatar answered Sep 23 '22 19:09

Paige Ruten


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.

like image 45
paxdiablo Avatar answered Sep 20 '22 19:09

paxdiablo