Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 705
Davita Avatar asked Aug 30 '11 20:08

Davita


2 Answers

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.

like image 99
Kevin Avatar answered Oct 13 '22 22:10

Kevin


No, the increment happens after the assignment.

If it were *(++p), the pointer p would be incremented and after that assigned.

like image 26
Alexey Ivanov Avatar answered Oct 13 '22 21:10

Alexey Ivanov