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
}

      

+2


source to share


4 answers


*s1 = *s2

      



Is an expression. Expressions in C / C ++ evaluate to values, in which case it returns the value assigned *s1

. When '\0'

assigned *s1

, the expression evaluates to 0

that which is explicit false

.

+5


source


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.

+2


source


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.

0


source


is code like this, check the extra parentheses I added ...:

void mystery1( char *s1, const char *s2 )
{
  while ( *s1 != '\0' )
  {
    s1++; 
  }

  for ( ; *s1 = *s2; s1++, s2++ )
  {
    ; // empty statement
  }
}

      

therefore, first checking the end of string s1; and for a copy of s2 at the end of s1.

0


source







All Articles