这是deitel的c ++书籍,我试图更多地了解为什么延续条件有效以及它如何知道退出。 s1和s2是数组,所以当s2试图将'\ n'分配给s1时它是否返回null?
void mystery1( char *s1, const char *s2 )
{
while ( *s1 != '\0' )
s1++;
for ( ; *s1 = *s2; s1++, s2++ )
; // empty statement
}
答案 0 :(得分:5)
*s1 = *s2
是一个表达。 C / C ++中的表达式求值为值,在这种情况下,它返回分配给*s1
的值。将'\0'
分配给*s1
后,表达式会清楚地评估为0
false
。
答案 1 :(得分:2)
是。它必须是一个布尔表达式,可以是其中的任何内容。
其工作方式如下:
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
}
}
这样做是将s2中的所有字符复制到s1的末尾,基本上将s2附加到s1。
为了清楚起见,\n
与此代码无关。
答案 2 :(得分:0)
该代码与'\ n'无关。赋值表达式的结果是赋值变量的新值,因此当您将“\ 0”赋给*s1
时,该表达式的结果为“\ 0”,将其视为false。循环遍历整个字符串被复制的点。
答案 3 :(得分:0)
是这样的代码,检查我添加的额外括号......:
void mystery1( char *s1, const char *s2 )
{
while ( *s1 != '\0' )
{
s1++;
}
for ( ; *s1 = *s2; s1++, s2++ )
{
; // empty statement
}
}
所以,首先检查字符串s1的结尾;以及s1末尾的副本s2。