代码之家  ›  专栏  ›  技术社区  ›  alex

K&R教学可读性差吗?

  •  2
  • alex  · 技术社区  · 14 年前

    我只是想去 练习5-3

    编写函数strcat的指针版本,我们在第2章中展示了这个函数:strcat(s,t)将字符串t复制到s的末尾。

    我想到了 this ...

    void strcat(char *s, char *t);
    
    void strcat(char *s, char *t) {
    
        while (*s++ != '\0');
        s--;
        while (*t != '\0') {
            *s++ = *t++;
        }
    
        *--t = '\0';
    
    }
    
    int main() {
       char str[] = "Hey, hello";
       char str2[] = " are you?";
    
       strcat(str, str2);
    
       printf("%s\n", str);
    
       return 0;
    
    }
    

    我想知道的是,K&R的书经常用尽可能少的行来编写练习——我想如果他们为上面的内容提供了自己的代码示例,你会得到这样的结果 this ...

    void strcat(char *s, char *t) {
    
        while (*s++ != '\0');
        s--;
        while ((*s++ = *t++) != '\0');
        *--t = '\0';
    
    }
    

    对我来说,这是不可读的(也许这个例子不太好,但我经常看他们的代码,然后思考 如果把它分成几行,我会理解得更好

    即使易读性受到影响,这本书在尽可能多的地方做你能做的事是对的吗?

    这只是 C路 ?

    3 回复  |  直到 14 年前
        1
  •  13
  •   gregjor    14 年前

    K&R在书中解释了习语的重要性。是的,C程序员很重视代码的简洁性,但并不是故意简明扼要地惩罚初学者。经过一段时间的读写,你开始识别模式,所以当你在别人的代码中看到它们时,你就知道你在看什么。

    strcpy() 以K&R为例,他们解释了简洁与清晰的哲学,并讨论了习语。

        2
  •  5
  •   Roland Illig    14 年前

    未定义的行为 .

    str 是11字节长, str2 是10字节长)。然后,在 strcat ,你试图写信给 str[11]

    而且,你不应该改变 *t 在里面 字符串连接函数 t 具有类型 const char * .

    第三,当重新实现一个也由您的环境提供的函数时,请给它另一个名称。否则编译器可能会用一些与函数调用等效的内置代码替换它。例如,GCC有 __builtin_strlen 有时会取代 strlen .

    代码的固定版本如下所示:

    #include <stdio.h>
    
    /* renamed strcat to str_cat to avoid confusing the compiler */
    void str_cat(char *s, const char *t) { /* added the const qualifier to t */
    
        while (*s++ != '\0');
        s--;
        while (*t != '\0') {
            *s++ = *t++;
        }
        /* removed the needless modification of *t */
        *s = '\0'; /* edit: added this line after the comment from Jonathan Leffler */
    }
    
    int main() {
       char str[80] = "Hey, hello"; /* note the large array size here */
       char str2[] = " are you?";
    
       str_cat(str, str2);
       printf("%s\n", str);
    
       return 0;
    
    }
    
        3
  •  0
  •   dawg    14 年前

    Other more readable, more efficient examples 可以通过使用 Google Codesearch .

    看看Android和BSD的源代码,尤其是更现代的C实现 strcat .

    而不是 字符串连接函数 你应该写一个 strlcat many examples 也可以找到这个来源。