while** = * t!=‘\ 0’是什么意思?

问题描述

在这里阅读有关K&R书中的指针

https://hikage.freeshell.org/books/theCprogrammingLanguage.pdf

然后,解释什么strcpy完全按照其书面内容进行操作:

/* strcpy: copy t to s; pointer version */
void strcpy(char *s,char *t) {
  while ((*s = *t) != ’\0’) {
    s++;
    t++;
  }
}

但是我不明白while ((*s = *t) != ’\0’)中有2个()行。

我了解到的是将其用作:while( condition )

解决方法

98
87
79
78
69
98
98

实际上,有一个分配,然后是一个比较:

  1. while ((*s = *t) != ’\0’)
  2. 如果等于循环结束,则将此字符的值与*s = *t; // copy the character *t in the string s比较

为了减少代码行数,将它们全部放在一行中。

,

这是一种非常密集的书写方式:

void strcpy(char *s,char *t) {
  while (true) {
    // The condition in the loop in your question
    *s = *t;
    if (*s == '\0)
      break;
    // The body in the loop in your question
    s++;
    t++;
  }
}

K&R书中较短的(在代码行中)版本有效,因为表达式(*s = *t)有两件事:

  1. 它将*s中的值分配给*t
  2. 表达式(*s = *t)的值为*t

因此,如果将*t分配给*s*t == '\0',我们可以用它打破循环。