Chen
Chen

Reputation: 147

Why while (*s++ != '\0') doesn't work?

I wrote a function copies the string t to the end of s, it works if I write like this

    char strcat(char *s, char *t) {
    while (*s != '\0')
        s++;
    while ((*s++ = *t++) != '\0')
        ;
    }

However, it doesn't work if I write it like this

    char strcat(char *s, char *t) {
    while (*s++ != '\0')
        ;
    while ((*s++ = *t++) != '\0')
        ;
    }

I don't understand what's the difference between

while (*s++ != '\0')
        ;

and

while (*s != '\0')
        s++;

Upvotes: 2

Views: 2012

Answers (1)

R Sahu
R Sahu

Reputation: 206577

When you use

while (*s++ != '\0');

s points to one character past the null character when the loop breaks. You end up copying the contents of t to s but after the null character.

If s is "string 1" before the function and t is "string 2", at the end of the function, you will end up with a character array that will look like:

{'s', 't', 'r', 'i', 'n', 'g', ' ', '1', '\0', 's', 't', 'r', 'i', 'n', 'g', ' ', '2', '\0', ... }
                                         ^^^^

Due to the existence of the null character in the middle, you won't see "string 2" in most uses.

On the other hand, when you use:

while (*s != '\0')
        s++;

s points to the null character when the loop breaks. Given the same input, you will end up with a character array that will look like:

{'s', 't', 'r', 'i', 'n', 'g', ' ', '1', 's', 't', 'r', 'i', 'n', 'g', ' ', '2', '\0', ... }
                     No null character in the middle.

Upvotes: 12

Related Questions