How it works in C? (implement strcat function) [closed]

The purpose of the code is to make dest point just after the last character of the destination string so that the characters from the source string can be added from that point and forward.

The bad thing about while(*dest++) is that it always increments dest, i.e. even when *dest is NUL ('\0'), dest will be incremented. So, in order to “get back” to the NUL, a decrement of dest is needed after the loop.

The code:


is equivalent to:

    char tmp = *dest;        // Save current value in tmp
    dest++;                  // Increment dest
    if (tmp == '\0') break;  // Check tmp and stop the loop if it's NUL

dest--;                       // Compensate for the unwanted increment

The code should just have been:

while(*dest) dest++;

In that way the increment is only done when needed (so there is no longer a need for the decrement)


Make sure to initialize str1 to something – at least do:

char str1[20] = "";

Leave a Comment