多个"for"循环语句没有块

Jay*_*esh -2 c for-loop

下面的代码片段在接受采访时给了我,并问我,是否有可能在没有阻塞的情况下评估for循环的所有语句?

int i, n, t1 = 0, t2 = 1, nextTerm;

for(int i= 0; i < 10; i++)
{
    printf("%d ", t1);
    nextTerm = t1 + t2;
    t1 = t2;
    t2 = nextTerm;
}
Run Code Online (Sandbox Code Playgroud)

我问他,我认为不可能在没有块的情况下评估for循环的多个语句.但是,我的朋友告诉我,可以使用逗号运算符,如下所示:

int i, n, t1 = 0, t2 = 1, nextTerm;

for(int i= 0; i < 10; i++)
    printf("%d ", t1),
    nextTerm = t1 + t2,
    t1 = t2,
    t2 = nextTerm;
Run Code Online (Sandbox Code Playgroud)

我知道comma运营商如何为单行声明工作.但我想知道如何comma为多线工作?

另外,还有其他方法可以完成这项任务吗?

Ken*_*Y-N 6

注意,不要像上面那样编写代码或者像我要做的那样!

你有一个关于多行的答案,但关于另一种写这个方法的另一个问题是:

for(int i= 0; i < 10; nextTerm = t1 + t2,
                      t1 = t2,
                      t2 = nextTerm,
                      i++)
    printf("%d ", t1);
Run Code Online (Sandbox Code Playgroud)

甚至,走到极端......

for(int i= 0; i < 10; printf("%d ", t1),
                      nextTerm = t1 + t2,
                      t1 = t2,
                      t2 = nextTerm,
                      i++)
    /* Hey, empty loop! */;
Run Code Online (Sandbox Code Playgroud)


Lun*_*din 5

一个单行语句,格式化为多行.

像这样使用逗号运算符完全是胡说八道.删除块完全没有任何目的 - 它只会使你的代码更危险,更难阅读,因为绝对没有任何好处.使用分号.

循环后始终使用复合语句.即使循环中只有一个单一的声明 - 历史上最昂贵的错误之一,"Apple gotofail"是由于松散使用大括号造成的.

  • 可能值得添加链接到这个"Apple gotofail"的解释 - > https://nakedsecurity.sophos.com/2014/02/24/anatomy-of-a-goto-fail-apples-ssl-bug-explained -plus-an-unofficial-patch//或发布它的代码并在你的答案中解释它 (2认同)