What is an example in which knowing C will make me write better code in any other language?

前端 未结 20 1169
独厮守ぢ
独厮守ぢ 2021-02-05 12:40

In the Stack Overflow podcasts, Joel Spolsky constantly harps on Jeff Atwood about Jeff not knowing how to write code in C. His statement is that \"knowing C helps you write bet

20条回答
  •  时光取名叫无心
    2021-02-05 13:20

    For the purposes of argument, suppose you wanted to concatenate the string representations of all the integers from 1 to n (e.g. n = 5 would produce the string "12345"). Here's how one might do that naïvely in, say, Java.

    String result = "";
    for (int i = 1; i <= n; i++) {
        result = result + Integer.toString(i);
    }
    

    If you were to rewrite that code segment (which is quite good-looking in Java) in C as literally as possible, you would get something to make most C programmers cringe in fear:

    char *result = malloc(1);
    *result = '\0';
    for (int i = 1; i <=  n; i++) {
        char *intStr = malloc(11);
        itoa(i, intStr, 10);
        char *tempStr = malloc(/* some large size */);
        strcpy(tempStr, result);
        strcat(tempStr, intStr);
        free(result);
        free(intStr);
        result = tempStr;
    }
    

    Because strings in Java are immutable, Integer.toString creates a dummy string and string concatenation creates a new string instance instead of altering the old one. That's not easy to see from just looking at the Java code. Knowing how said code translates into C is one way of learning exactly how inefficient said code is.

提交回复
热议问题