Home > Mobile >  I have problem understanding the condition of the following while loop
I have problem understanding the condition of the following while loop

Time:12-26

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?

CodePudding user response:

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.

CodePudding user response:

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;
}
  • Related