Understanding a certain loop

Hi
I am very new to programming and i am reading a book called "Discovering Modern C++" by Peter Gottschling. Very early in the book the author sets up an example of what he calls a piece of excellent programming.

The author writes following:
"In the C standard library, there is a function to copy a string (strcpy). The function takes pointers to the first char of the source and the target and copies the subsequent letters until it finds a zero. This can be implemented with one single loop that even has an empty body and performs the copy and the increments as side effects of the continuation test:
while (*tgt++= *src++) ;"

I've been struggling to understand how this really works, which maybe has to do with the fact that i don't really know how pointers work with chars/strings. Can anyone explain this line of code in layman/newbie language? I'd really like to understand the mechanics behind this line.

Thanks

 
  while (*tgt++= *src++) ;
We have three operators in the mix: dereference, post-increment and assignment.
Make it four, there is an implicit conversion from a char to bool too.

Multiple operators. Who goes first? Precedence and order of evaluation.

The right side of assignment reads a char that the pointer src is pointing to and after that advances the pointer to next char.

On the left side the char from right side is assigned to where-ever the tgt points to and after that the tgt is advanced.

Testing the condition is the last step. We can rewrite the whole as equivalent do..while loop:
1
2
3
4
5
6
7
char result = '\0';
do {
  *tgt = *src;
  result = *tgt;
  ++src;
  ++tgt;
} while ( result );

A C-string is an array of characters. The last character in it is null ('\0'). Null converts to false. Thus, when the last character has been copied, the condition is false and the loop ends.

After the loop the src points one past the null of the original string.
After the loop the tgt points one past the null of the new string.
That cleared it up! :)

Thanks a lot! Really appreciated!
Topic archived. No new replies allowed.