Search code examples
cpointerspost-increment

Post-increment in a while loop


The following code confused me a bit:

char * strcpy(char * p, const char * q) {
  while (*p++=*q++);
  //return
}

This is a stripped down implementation of strcpy function. From this code, we see that pointer p and q are incremented then dereferenced and q is assigned to p until the \0 char has been reached.

I would like someone to explain the first iteration of the while loop.


Solution

  • Because the ++ is after the variables, they aren't incremented until after the expression is evaluated. That's why it's the post-increment operator; the pre-increment is prefixed (++p). *++p would write to the second spot, *p++ writes to the first.