Peter
Peter

Reputation: 93

copy a string into another C

in the K&R book the following is given as initial (and correct) function to copy a string

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

Then it's said that an equivalent function would be

void strcpy (char *s, char *t)
{
    while (*s++ = *t++)
        ;
}

I don't understand how the while loop can stop in the second case.

Thanks

Upvotes: 2

Views: 105

Answers (3)

Michael Burr
Michael Burr

Reputation: 340198

The simple assignment expression has two effects:

1) stores the value to the lvalue on the left hand side (this is known as a 'side-effect')

2) the expression itself evaluates to a value - the value of what assigned to that lvalue

A while loop will repeat until its condition evaluates to 0. So the loop in the second example runs until the value 0 is assigned to the destination string.

Upvotes: 4

haccks
haccks

Reputation: 106012

The expression *s++ = *t++ has also a value after evaluation. If it evaluates to non zero value then condition is true otherwise false.

while (*s++ = *t++) is equivalent to while ((*s++ = *t++) != 0).

Upvotes: 2

Haris
Haris

Reputation: 12270

It is happening because for an expression, the result of the expression is returned.

if( (a = 4) == 4)

This if statement will evaluate to True.


So, in your case

while (*s++ = *t++)

when it reaches the NUL character \0, it will evaluate to False, and the loop will exit.

Upvotes: 2

Related Questions