cif-statementwhile-loopcharstrncpy

The loop of the strncpy function is not understood


char *strncpy(char *dest, const char *source, size_t n) {
  char *start = dest;

  while (n && (*dest++ = *source++)) n--;
// I don't understand from the code below this
// I know I put'\0' at the end of dest.
// But I don't know how if (n) while (--n) works.
  if (n) while (--n) *dest++ = '\0';
  return start;
}

http://www.jbox.dk/sanos/source/lib/string.c.html#:38


Solution

  • The stylistic decisions of this code make it difficult for a newer developer to read. A quick run through a beautifier gives this result (with my own comments added).

    //takes a destination string, a source string, and a size (count) of characters to copy
    char * strncpy(char * dest, const char * source, size_t n) {
    
      //create a pointer to the start of the destination string
      char * start = dest;
    
      //run this loop until one of two things happens: 
      //- n hits 0, meaning we've copied the required number of characters
      //- the assignment operator '=' returns '\0', indicating that we've just copied
      //  a '\0' into dest - this means we've hit the last character in source.
      while (n && ( * dest++ = * source++)) {
        n--;
      }
    
      //this checks to see if n still has leftover value - if it does, it means that
      //source had fewer characters than we were asked to copy
      if (n) {
        //we will now go through the remaining characters and pad the returned string
        while (--n) {
          //add '\0' to the return string
          * dest++ = '\0';
        }
      }
    
      return start;
    }