4
int main()
{
char str1[] = "Overflow";
char str2[] = "Stack";
char *s1 = str1, *s2=str2;
while(*s1++ = *s2++)
printf("%s", str1);
return 0;
}

当这个条件被打破时

(while(*s1++ = *s2++))

请解释逻辑

输出是

在此处输入图像描述

4

5 回答 5

4

*s1++,在这个变量中,*的优先级高于 ++。在下面的代码中,

while(*s1++ = *s2++); //There should be a semicolon.Your code does not has.
  1. *s1 = *s2首先被评估。
  2. 几乎 C 中的每个表达式都返回一个值。所以*s1 = *s2返回一个值,它是第一个字符,它显然不为空。while()循环被执行。
  3. 然后s1s2递增。
  4. s2到达字符串的末尾时,*s2返回'\0'分配给的s1*s1=*s2. 现在这个表达式也返回一个值'\0'并且while('\0')循环终止。
于 2013-11-15T07:06:58.693 回答
3

This while loop relies on the fact that non-zero evaluates as true in any conditional expression in C.

It's probably clearer to work the other way, from the more obvious way of doing this operation, to this shorthand.

You can start with:

while(*s2 != '\0')
{
    *s1 = *s2;
    s1++;
    s2++;
}

This means 'while s2 hasn't reached a terminator character, keep copying characters from s2 to s1. Move both pointers forward after each copy to get ready for the next copy.

However, this can be shortened by including the increment operation in the same line as the copy. This is safe because it's a post-increment operation. It won't evaluate till the copy has already been done. The code now looks like this:

while(*s2 != '\0')
{
    *s1++ = *s2++;
}

Now, given that nonzero is equivalent to true, we can simplify further. The *s2 != '\0' is equivalent to just *s2 on its own.

while(*s2)
{
    *s1++ = *s2++;
}

Finally, we can move the copy itself into the while statement. The while statement itself will copy the character from *s2 to *s1 and then evaluate *s1 as before. The increment then happens afterwards, and round it goes. So our code looks like this:

while(*s1++ = *s2++);

So.. in your case you need a semicolon after your while statement, or it will print multiple times.

于 2013-11-15T07:18:20.420 回答
3

运算符的优先级*高于++运算符,因为在您的表达式中

while(*s1++ = *s2++) 

s1 在增量之前首先由 s2 分配,因此评估顺序将是

1.*s1=*s2;

2.s1++,s2++

3 printf("%s",str1),这里str1的值由于操作1而改变

4.当 s2 到达结束时循环终止条件出现,'\0'并且由于*s1=*s2上述指定,该值被分配给 s1,并且 s1 的值变为 null =>s1='\0'并且 while 循环终止

于 2013-11-15T12:39:33.883 回答
2

此循环将复制内容str2into str1

while(*s1++ = *s2++);

当遇到 str2 中的最后一个字节(为 0)时,if 将停止。

换句话说,str1[] = "Overflow"会变成str1[] = "Stacklow"


更新:更详细的解释。

  • 在第一个循环中,您只复制 1 个字符str2,即S. 所以str1Overflow变成Sverflow
  • 第二个循环,它变成Sterflow.
  • 第三个循环,它变成Starflow.
  • 第 4 个循环,它变成Stacflow.
  • 第 5 次循环,它变成Stacklow.

请注意,这些是屏幕截图中可见的行。

之后,遇到 0 字节并复制到str1,因此变为Stack\0ow,但您不打印它。如果要打印它,它只会打印Stack.

于 2013-11-15T07:06:58.130 回答
0

它将循环直到在 s2 中遇到字符串终止符('\0')

while(*s1++ = *s2++)
printf("%s", str1);

while(*s1++='S') prints "Sverflow"
while(*s1++='t') prints "Sterflow"
while(*s1++='a') prints "Starflow"
while(*s1++='c') prints "Stacflow"
while(*s1++='k') prints "Stacklow"
while(*s1++='\0') ends loop 
于 2013-11-15T07:15:39.660 回答