Possible Duplicate:
How does “while(*s++ = *t++)” work?
I was trying to understand the following example. I am a little confused how this would actually work.
void strcpy(char *s, char *t)
{
while (*s++ = *t++)
;
}
Any help is great. Thanks!
Possible Duplicate:
How does “while(*s++ = *t++)” work?
I was trying to understand the following example. I am a little confused how this would actually work.
void strcpy(char *s, char *t)
{
while (*s++ = *t++)
;
}
Any help is great. Thanks!
Remember that a string in C is just a pointer to a list of chars, terminated with a \0
.
Also remember that \0
(the null byte) is falsy, that is, if it's in a condition, that condition will be false.
This function gets a pointer to the start of the source string and one to the start of the destination string.
It then loops over each character in the source string, copying the character to the destination string. When the condition is evaluated, the post-increment ++
will advance the pointer forward a byte.
This implementation also has an issue, as far as I can tell. If the source string isn't the exact same length, it won't have a null terminator at the end. For safety's sake, you should tack a \0
at the end of the destination string.
The value of *s++ = *t++
is the value of the right side of the assignment, *t
. So the loop will terminate when *t is 0, i.e., at the end of the string pointed by t. The condition also increments the value of t
(and s
), after assigning the character pointed by t
to the char pointed by s
. There is nothing in the loop body, the condition by itself does the copy.