【问题标题】:Is this kind of code considered good by today's standards? [closed]按照今天的标准,这种代码是否被认为是好的? [关闭]
【发布时间】:2013-10-08 10:26:04
【问题描述】:

我刚刚在 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 出现的方式,因为在循环期间执行的代码周围没有括号。

【问题讨论】:

  • 太主观了。如果您让我们开始,我们可以整天为编码风格指南而战。 :)
  • 我不会那样写的。这就够了吗?
  • 也会不符合 MISRA 编码标准。
  • 我根本不会使用else,你有一个return...

标签: c coding-style


【解决方案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");

【讨论】:

    猜你喜欢
    • 2011-08-12
    • 2011-02-14
    • 1970-01-01
    • 1970-01-01
    • 2011-06-11
    • 2012-11-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多