views:

278

answers:

7

Looking at this loop that copies one c-string to another:

void strcpyr(char *s, char *t)
{
    while(*s++=*t++)// Why does this work?
        ;
}

Why do we not check for the '\0' character in the while loop, like this?

while((*s++=*r++)!='\0')..

How does the first loop terminate?

+4  A: 

When we hit the '\0' in the string initially pointed to by t, the *s++=*t++, which does the assignment, also returns the value that's assigned to the position pointed to by s, or '\0', which evaluates to false and terminates the loop.

In your second example, you explicitly rely on the fact that the assignment returns the assigned character, while the first example implicitly uses this fact (and the fact that the 0 character (also written '\0') is considered to be false, while all other characters evaluate to true, so the expression c != '\0' will yield the same result as c.

Blair Conrad
+1  A: 

The reason we are not explicitly checking for zero is that in C 0 is false.

Therefore the loop

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

will terminate when the character pointed to by t is 0.

Adam Davis
+2  A: 

The loop is going to terminate because '\0' is effectively 0, and the what the "while" is evaluating is not a the result of an equality test (==), but the right-value of the assignment expression.

florin
+12  A: 

The statement *s++=*t++ not only assigns the next character from t to s but also returns the current value of *t as the result of the expression. The while loop terminates on any false value, including '\0'.

Think of it this way. If you did:

char c = *s++ = *t++;

in addition to copying a char from *t to *s and incrementing both, it would also set c to the current value of *t.

Ferruccio
A: 

I think you mean to write this:

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

The loop terminates when the value pointed to by "t" is zero. For C (and C++) loops and conditionals, any integer that is non-zero is true.

Joseph Bui
A: 

The while loop is testing the result of the assignment. The result of an assignment is the value assigned into the left-hand side of the statement. On the last iteration, when *t == '\0', the '\0' is assigned into s, which becomes the value the while loop considers before deciding it is time to quit.

fadein
A: 

In C, a=b is actually an expression which is evaluated as 'b'. It is easier to write:


if(a=b) {
 //some block
}

then:


a=b;
if(a!=0) {
 //some block
}

In C language within if, while, for statement the check that is made is: is expression not zero?

botismarius