开发者

Can the loop continuation condition in for loop be anything that will eventually return a false/null value?

This is out of deitel's c++ book and I'm trying to understand a bit more about why the continuation condition works and how it knows to quit. s1 and s2 are arrays so when s2 tries to assign the '\n' to s1 does it return null?

void mystery1( char *s1, const char *s2 )
{
while ( *s1 !=开发者_如何学Python '\0' )
s1++;

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


*s1 = *s2

Is an expression. Expressions in C/C++ evaluates to values, and in this case it returns the value assigned to *s1. When the '\0' is assigned to *s1, the expression evaluates to 0 which is false clearly.


Yes. It must be a boolean expression, can be anything inside of it.

The way this works is as follows:

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 does is copy all characters from s2 onto the end of s1, basically appending s2 to s1.

Just to be clear, \n has nothing to do with this code.


That code has nothing to do with '\n'. The result of an assignment expression is the new value of the assigned-to variable, so when you assign '\0' to *s1, the result of that expression is '\0', which is treated as false. The loop runs through the point where the entire string is copied.


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

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

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

so, first while checks the end of the string s1; and the for copy s2 at the end of s1.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜