1

In the K&R C Programming book, I came across this code snippet for string copying:

/* strcpy: copy t to s; pointer version 3 */
void strcpy(char *s, char *t)
{
while (*s++ = *t++)
;
}

This correctly copies two character arrays (of course it does). My question is, why does it work the way it does? There doesn't seem to be any condition checking inside the while. There is an assignment and a post increment. My gut feeling is that this always evaluates to true (similar to how while(1) always evaluates to true, and we need a break somewhere to get out of the loop.

There is nothing inside of the loop either. No bound checking, no ifs, nothing. It all seems very risky and reckless to me. Can someone walk me through this? Thanks.

nirvanaswap
  • 859
  • 2
  • 11
  • 21

2 Answers2

8

The operator = always produces a return value: the value of the right operand. (This is why x = y = z = 5 is a valid expression.) When you reach the end of a string, *t++ points to '\0'. This character evaluates as false, this is why it makes the while loop stop.

The '\0' character is also called NUL and this is the only character which evaluates as false because its decimal value is 0, and all other characters have a decimal value other than 0. (This corresponds with the well-known fact that the number 0 evaluates as false and all other numbers are evaluated as true.)

Here is a thread on this topic.

Community
  • 1
  • 1
Andrea Dusza
  • 2,080
  • 3
  • 18
  • 28
  • Perfect! This is probably a duplicate then. Thanks!! – nirvanaswap Dec 25 '15 at 03:56
  • actually the operator `=` produces the value of the *left* operand (what it would be after the assignment, to be precise). Example: `double d; int x; d = x = 5.5;` – M.M Dec 25 '15 at 05:59
2

s++ and t++ increments each pointer to point to the next character.

You can use asignments inside ifs so for example:

int a;
if (a = 3){
    // this code will always be executed
}

if (a = 0){
    // this code will never be executed
}

because the result of the assignment is used to check for the conditional. The assignment operator, returns the value of the assigned value.

Strings in c are terminated by '\0' which is 0.

char c = '\0'
if (c){
    // this code will never be executed
}

This way, when t points to 0, this will be assigned to *s and result of the assignment will also be 0 so the while loop will exit.

orestisf
  • 1,396
  • 1
  • 15
  • 30