Si. Copy character string

After going through K & R, I saw the following code fragment strcopy function, which copies an array of characters to another.

If t is a pointer to the first array, and s is a pointer to the array to which t is copied, the code:

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

I got confused in a while loop. I underestimate that inside the condition t is copied to s, but I don't understand which condition is being tested here. When will *t++ be false (or null)? Presumably when the character string ends. We can check if the line is complete by checking if the character pointed to by the character '\0' . K & R says the same. But then the book rather nonchalantly indicates that this test is not needed. So I wonder what is being tested here?

+4
source share
4 answers

*s++ = *t++ will evaluate the value that was assigned. At the end of the line *t will be '\0' , and when assigned, the expression will be evaluated as '\0' (which C interprets as false ).

I think K & R says no extra test is needed, since everything is processed in while .

+5
source
 *s++ = *t++; 

matches with:

 *s = *t; t++; s++; 

The condition always evaluates the left value, so in this case it is like testing

 while(*s) 

Of course, '\0' evaluates to false, so you don't need while(something!='\0') , because while(something) enough.

+6
source

You can check explicitly if the terminating character is reached with

 while ((*s++ = *t++) != '\0') ; 

if you look at "\ 0" in the ascii table, you will see that the character "\ 0" has an integer value of 0. Writing something like printf("%d\n", '\0'); will also confirm it.

So, the while statement above can also be written as

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

However, the while-loop always checks if the condition has a non-zero value, so it is always redundant to compare the value in the while loop against zero in this way. Therefore, you can simply skip the comparison.

+3
source

C assigns threads from right to left, and the while loop performs an implicit if test. So what compilers do in terms of test ...

 while(*t != 0) // for the sake off testing if the loop should continue ONLY 

Another example...

 if (a = b) // note the = vs == so, this will only be true if b != 0 

The kind of pseudo-code version of this loop ...

 loop: *s=*t; if (*s == 0) should_break=1; s++; t++; if (should_break==1) break; goto loop; 
0
source

All Articles