0

我刚刚在 K&R 的书中找到了这段代码,我想知道今天的最佳实践是否认为它是好的:

while ((len = getline(line, MAXLEN)) > 0)
    if (nlines >= maxlines || (p = alloc(len)) == NULL)
        return -1;
    else {
        line[len-1] = '\0'; /* delete newline */
        strcpy(p, line);
        lineptr[nlines++] = p;
    }

具体来说:

  • 出现的方式else,因为在循环期间执行的代码周围没有括号。
4

1 回答 1

1

对我来说,最佳实践是始终在每个if语句的两个分支周围使用括号。

为什么?因为它可以防止这个错误:

if (foo()) 
    if (bar()) printf("bar\n");
else
    printf("The else actually belongs to 'if (bar())', but due to the indentation it looks as it was meant to be the else of 'if (foo())'.\n");
于 2013-10-08T10:36:02.863 回答