Search code examples
cstringstrcpy

Need guidance with aspects of strcpy in C


This code is from strcpy in string.c I am trying to understand a few of the features here:

 char *(strcpy)(char *restrict s1, const char *restrict s2)
 {
     char *dst = s1;
     const char *src = s2;
     while ((*dst++ = *src++) != '\0')
         ;
     return s1;
 }

What is going on in this while loop?

(*dst++ = *src++)

Thanks.


Solution

  • (*dst++ = *src++)

    There is a lot going on here. The first thing to note is that this is assigning the value of *src++ to *dst++. The asterisk dereferences both dst++ and src++, so this is an assignment of one char to another. Note that the ++ operator has higher precedence than the * (dereference) operator. See https://en.cppreference.com/w/c/language/operator_precedence.

    The second important detail is that the increments are postfix; ++ is to the right of the variables dst and src. So dst and src are only incremented after the check inside the while is complete. Effectively, this sets the first character in dst to be the first character in src.

    So, dst and src increment by one each time the first character of src is not the zero character \0.

    For your second question, see What do the parentheses around a function name mean?.

    src is declared a const char * because the character(s) it points to are not being modified and this is generally good practice. There are lots of discussions on this on the internet; e.g. https://dev.to/fenbf/please-declare-your-variables-as-const. Note that src itself (the pointer) is clearly modified in the while loop.