Akos Nagy Akos Nagy - 4 years ago 103
C Question

Are the following two functions equivalent? If not, why not?

void s1(char dest[], char src[])
{
int i=0;
while(dest[i++]=src[i++]);
}

void s2(char * dest, char *src)
{
while(*dest++=*src++);
}


Also, note that I took this problem from a book, and don't know if the code is correct or not(I think there should be two '=' in the while loop)

Answer Source

The second code performs a string copy. It is equivalent to strcpy().

The first code has undefined behaviour because it updates i twice in one statement without an intervening sequence point.

So the answer is that they are not the same.

The first code could be corrected. For example like this:

void s1(char dest[], char src[])
{
    int i=0;
    while(dest[i]=src[i]) i++;
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download