int main()
{
char str1[] = "Overflow";
char str2[] = "Stack";
char *s1 = str1, *s2=str2;
while(*s1++ = *s2++)
printf("%s", str1);
return 0;
}
当这个条件被打破时
(while(*s1++ = *s2++))
请解释逻辑
输出是
*s1++
,在这个变量中,*
的优先级高于 ++
。在下面的代码中,
while(*s1++ = *s2++); //There should be a semicolon.Your code does not has.
*s1 = *s2
首先被评估。*s1 = *s2
返回一个值,它是第一个字符,它显然不为空。while()
循环被执行。s1
和s2
递增。s2
到达字符串的末尾时,*s2
返回'\0'
分配给的s1
。*s1=*s2
. 现在这个表达式也返回一个值'\0'
并且while('\0')
循环终止。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.
运算符的优先级*
高于++
运算符,因为在您的表达式中
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 循环终止
此循环将复制内容str2
into str1
:
while(*s1++ = *s2++);
当遇到 str2 中的最后一个字节(为 0)时,if 将停止。
换句话说,str1[] = "Overflow"
会变成str1[] = "Stacklow"
。
更新:更详细的解释。
str2
,即S
. 所以str1
从Overflow
变成Sverflow
。Sterflow
.Starflow
.Stacflow
.Stacklow
.请注意,这些是屏幕截图中可见的行。
之后,遇到 0 字节并复制到str1
,因此变为Stack\0ow
,但您不打印它。如果要打印它,它只会打印Stack
.
它将循环直到在 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