Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading