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!
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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
\0at the end of the destination string.