[英]copy a string into another C
in the K&R book the following is given as initial (and correct) function to copy a string 在K&R书中,下面给出了复制字符串的初始(和正确)函数
void strcpy (char *s, char *t)
{
while ( (*s++ = *t++) != '\0')
;
}
Then it's said that an equivalent function would be 然后据说有一个等价函数
void strcpy (char *s, char *t)
{
while (*s++ = *t++)
;
}
I don't understand how the while loop can stop in the second case. 我不明白while循环如何在第二种情况下停止。
Thanks 谢谢
The simple assignment expression has two effects: 简单赋值表达式有两个效果:
1) stores the value to the lvalue on the left hand side (this is known as a 'side-effect') 1)将值存储在左侧的左值(这被称为'副作用')
2) the expression itself evaluates to a value - the value of what assigned to that lvalue 2)表达式本身求值为一个值 - 分配给该左值的值
A while
loop will repeat until its condition evaluates to 0. So the loop in the second example runs until the value 0 is assigned to the destination string. while
循环将重复,直到其条件计算为0.因此第二个示例中的循环将运行,直到将值0分配给目标字符串。
It is happening because for an expression, the result of the expression is returned. 它正在发生,因为对于表达式,返回表达式的结果。
if( (a = 4) == 4)
This if
statement will evaluate to True
. 此
if
语句将计算为True
。
So, in your case 所以,在你的情况下
while (*s++ = *t++)
when it reaches the NUL
character \\0
, it will evaluate to False
, and the loop will exit. 当它到达
NUL
字符\\0
,它将评估为False
,循环将退出。
The expression *s++ = *t++
has also a value after evaluation. 表达式
*s++ = *t++
在评估后也有一个值。 If it evaluates to non zero value then condition is true
otherwise false
. 如果它的计算结果为非零值则条件为
true
否则为false
。
while (*s++ = *t++)
is equivalent to while ((*s++ = *t++) != 0)
. while (*s++ = *t++)
等同于while ((*s++ = *t++) != 0)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.