Derteck
Derteck

Reputation: 101

Question: What is this while loop with this particular condition doing?

char *strcpypp(char *dest, char *orig)
{
   char *tmp = dest;
   while (*dest++ = *orig++)
      ;

return tmp;
}

What is this function really doing?.

Upvotes: 1

Views: 51

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 310990

For starters the function should be declared like

char *strcpypp(char *dest, const char *orig);

because the string pointed to by the pointer orig is not being changed in the function.

The variable tmp should be declared in a for loop.

So the function will look like

char * strcpypp( char *dest, const char *orig )
{
    for ( char *tmp = dest; *tmp++ = *orig++; );

    return dest;
}

The function copies the string pointed to by the pointer orig in the character array pointed to by the pointer dest.

The value of this expression

*tmp++ = *orig++

is the value assigned to the character pointed to by the pointer tmp before incrementing the pointers tmp and orig themselves.

So if the assigning character is the terminating zero character '\0' of the string pointed to by the pointer orig then it is assigned to the character pointed to by the pointer tmp and the condition of the loop evaluates to false because the value of the whole expression is equal to zero.

Upvotes: 1

Related Questions