Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'\0' related issue

Tags:

c++

string

Looking at this loop that copies one c-string to another:

void strcpyr(char *s, char *t)
{
    while(*s++=*t++)// Why does this work?
        ;
}

Why do we not check for the '\0' character in the while loop, like this?

while((*s++=*r++)!='\0')..

How does the first loop terminate?


2 Answers

The statement *s++=*t++ not only assigns the next character from t to s but also returns the current value of *t as the result of the expression. The while loop terminates on any false value, including '\0'.

Think of it this way. If you did:

char c = *s++ = *t++;

in addition to copying a char from *t to *s and incrementing both, it would also set c to the current value of *t.

like image 66
Ferruccio Avatar answered Dec 07 '25 20:12

Ferruccio


When we hit the '\0' in the string initially pointed to by t, the *s++=*t++, which does the assignment, also returns the value that's assigned to the position pointed to by s, or '\0', which evaluates to false and terminates the loop.

In your second example, you explicitly rely on the fact that the assignment returns the assigned character, while the first example implicitly uses this fact (and the fact that the 0 character (also written '\0') is considered to be false, while all other characters evaluate to true, so the expression c != '\0' will yield the same result as c.

like image 39
Blair Conrad Avatar answered Dec 07 '25 19:12

Blair Conrad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!