简体   繁体   中英

I have problem understanding the condition of the following while loop

void strcpy(char *s, char *t)
{
    int i;
    i = 0;
    while ((*s = *t) != '\0') {
        s++;
        t++;
    }
}

I made a function to copy string t to string s using pointers from K&R. The while loop uses (*s = *t)!='\0' which is supposed to mean that to run loop till the we reach the end of t string but I didn't understand how it works, According to me: when the end is reached s gets '\0' in end so it got assigned but how the comparision of this is made with !='\0' part, does the bracket (*s=*t) returned '\0' in end and then it is compared and the loop is ended?

Generally, the line

if ( ( a = b ) != c )

is equivalent to the following:

a = b;
if ( a != c )

This is because the sub-expression ( a = b ) evaluates to the new value of a .

For the same reason, in the line

while ((*s = *t) != '\0')

the sub-expression ( *s = *t ) will evaluate to the new value of *s , so the loop condition is effectively *s != '\0' , where *s is the new value, which is the value of *t .

So yes, you are correct that the loop will end as soon as *t becomes a null character.

It can be written in the shorter form. The function should also return something.

char *strcpy(char *dest, const char * restrict src)
{
    char *wrk = dest;
    while ((*wrk++ = *dest++));
    return dest;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM