strcpy or fun with pointers, a while loop and cstrings

ps1 and ps2 are pointers to a character array, what does this do?
while (*ps2++=*ps1++);

It is my favorite example of bizarre looking C code which utilizes pointers, pointer increments, unary operation precedence, C-string null termination and the evaluation of an assignment. Breaking it down a little "*ps2++=*ps1++" means the same thing as this:
*ps2 = *ps1;
ps2++;
ps1++;

Since ps1 and ps2 are character pointers the first line dereferences each and sets the value of ps1 to the memory pointed to by ps2. The second and third lines just increment each pointer. Both are pointing to character arrays, so they now point to the next character in the array.

The final important detail is that a cstring ends with a null terminator. So eventually the loop will get to the strings end and assign "'\0' = '\0'", which evaluates to '\0', which is false. Thus ending the loop.

Here's a full example:


Here it is in the form of strcpy (from wikipedia):

Comments

Popular posts from this blog

Taking Stuff Apart: Realistic Modulette-8

OpenSCAD linear extrude that interpolates between two shapes

XCode4: UITabBarController with UINavigationController using Interface Builder