Possible Duplicate:
How does “while(*s++ = *t++)” work?
I had the following question during an interview. Can someone please explain it to me?
void question( char *s, char *t)
{
while (*s++ = *t++);
}
Possible Duplicate:
How does “while(*s++ = *t++)” work?
I had the following question during an interview. Can someone please explain it to me?
void question( char *s, char *t)
{
while (*s++ = *t++);
}
It introduces a massive security vulnerability into your program. Do not write, or use, code like this under any circumstances.
If we break the code down, we get:
*t++
reads the character pointed to by t
, and increments t
; the expression's value is the character that was read.*s++ = expression
writes that character to where s
points, and increments s
; the expression's value is the character that was written.while (expression);
keeps looping as long as the expression's value is non-zero; in this case, until we wrote a character with the value zero.So the function keeps copying characters from t
to s
until it reaches a zero-valued character. There is no way to tell whether s
points to a large enough array to hold these, so in general it will write beyond the end of the array and cause undefined behaviour; anything from subtle behaviour with no unwanted effects, to a crash, to the execution of malicious code.
You can only call this function if you know in advance (an upper bound for) how many characters will be copied; if you know that, then there are (usually) more efficient ways to copy the data than to check the value of each. Therefore, you should (almost) never use this function, or the C library function (strcpy
) that it approximates.
This use of a zero-valued character to terminate a string is a common idiom in C; in C++ it is usually more convenient to use the std::string
class to represent strings instead. In that case, the equivalent code would be simply s = t
, which would manage the strings' memory safely.
Copies the string, pointer by t
to the memory, pointed by s
.
operator=
will return the assigned value. t
is supposed to point to a NULL
-terminated string and s
should point to memory, large enough to store that string.
So, the while
loop will stop when \0
is hit, which is the end of the string, pointed by t
. During this while
loop, all chars (different from \0
) in t
will be copied into s
.
Expanded a little, it's the same as:
while( *t != '\0' ) // while the current char is not NULL
{
*s = *t; // copy it into s
++s; // increment s, to point to the next byte
++t; // increment t, to point to the next char, that will be copied
}
*s = *t; // copy the last char of t - the '\0'
It copies null-terminated string t
into s
. Semantics as strcpy
.