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?
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:
*t
) are copied to s (*s
), one character.s
and t
are both incremented (++
).while
).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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With