Could the condition for continuing the loop in the loop be what will eventually return false / null?
This is from the C ++ deitel book and I am trying to understand a little more about why the continuation condition works and how it knows to terminate. s1 and s2 are arrays, so when s2 tries to assign '\ n' to s1 it returns null?
void mystery1( char *s1, const char *s2 )
{
while ( *s1 != '\0' )
s1++;
for ( ; *s1 = *s2; s1++, s2++ )
; // empty statement
}
source to share
Yes. It must be a logical expression, it can be anything inside.
How it works:
void mystery1( char *s1, const char *s2 )
{
while ( *s1 != '\0' ) // NEW: Stop when encountering zero character, aka string end.
s1++;
// NEW: Now, s1 points to where first string ends
for ( ; *s1 = *s2; s1++, s2++ )
// Assign currently pointed to character from s2 into s1,
// then move both pointers by 1
// Stop when the value of the expression *s1=*s2 is false.
// The value of an assignment operator is the value that was assigned,
// so it will be the value of the character that was assigned (copied from s2 to s1).
// Since it will become false when assigned is false, aka zero, aka end of string,
// this means the loop will exit after copying end of string character from s2 to s1, ending the appended string
; // empty statement
}
}
What this means is to copy all characters from s2 to the end of s1, basically adding s2 to s1.
To be clear, \n
has nothing to do with this code.
source to share
This code has nothing to do with '\ n'. The result of an assignment expression is the new value of the assigned variable, so when you assign '\ 0' to *s1
, the result of that expression is '\ 0', which is considered false. The loop goes through the point where the entire line is copied.
source to share