No I didn't come up with that myself (far to clever for me), but I think I understand how it works.
There are three important points you need to know:
1) When you march a pointer along an array, there is nothing to stop you from marching right past the end of the array and into memory that is not part of the array, and therefore that memory could contain anything. If you are lucky, marching past the end of an array and into memory that is not part of the array, will cause your program to crash. That's lucky because then you will know something is wrong with your program. If you are unlucky, your program will continue executing with some junk value.
2) c-style strings are char arrays that end in a \0, e.g.:
abc\0
When you write a statement like this:
char myStr[] = "abc";
the compiler first takes the "string literal"(i.e. anything between double quotes) and slaps a \0 on the end of it and stores it in memory. Then it performs a strcpy() into the myStr array, which also copies the \0.
3) A "boolean context" is some place in the code where a value must be interpreted as true or false, e.g.:
if( ..boolean context in here...)
or
while( ...boolean context in here... )
In a boolean context, the character '\0' will evaluate to false and any other character will evaluate to true. You can play around with this if statement to demonstrate that:
Code:
if('\0')
{
cout<<"true"<<endl;
}
else
{
cout<<"false"<<endl;
}
Try substituting some different characters in the if condition.
In this code:
Code:
void strcopy(const char* str1, char* str2)
{
while(*str2++ = *str1++);
}
The first thing that happens is that str1 is dereferenced to get the value it is pointing to(I'm fudging a little bit here as you will recognize if you look at an operator precedence table). Then that value is assigned to the value that str2 is pointing to, which is *str2. Then *str2 is evaluated in the boolean context. It's the same as if you did this:
Code:
int num;
if( num = 10)
{
//do something
}
That if statement does not check if num is equal to 10. Instead, it assigns 10 to num and then evaluates num in the boolean context. In that if statement, any number that is non-zero will evaluate to true, so that if statement is true. In your while statement:
Code:
void strcopy(const char* str1, char* str2)
{
while(*str2++ = *str1++);
}
if *str2 was assigned any character besides '\0', *str2 will evaluate to true. Finally, both str2 and str1 are advanced along their respective arrays. The while loop will ultimately terminate when *str1 is a '\0' character: the '\0' character will get assigned to *str2, which will be evaluated in the boolean context with the result being false. Note that by assumption you are dealing with c-strings, so str1 will end in a '\0', and you will not go marching off the end of the str1 array.