2
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?

Andreas Wenzel
  • 22,760
  • 4
  • 24
  • 39
Zolo_Ryan
  • 51
  • 6
  • 3
    Does this answer your question? [How does "while(\*s++ = \*t++)" copy a string?](https://stackoverflow.com/questions/810129/how-does-whiles-t-copy-a-string) – Harith Dec 26 '22 at 11:30
  • 1
    `i` is never used in your code. – Zakk Dec 26 '22 at 12:15
  • "when the end is reached s gets '\0' in end" Close, but wrong. No, `s` will not become `NULL` but `*s` will be a 0. – Gerhardh Dec 26 '22 at 13:48

2 Answers2

2

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.

Andreas Wenzel
  • 22,760
  • 4
  • 24
  • 39
0

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;
}
0___________
  • 60,014
  • 4
  • 34
  • 74