"for" 语句是如何构造的?

How is the "for" statement constructed?

每个人都知道 for 的最常见用法:(0 - 9)

for (int i = 0; i < 10; i++)

然而,我也看到了一些不太常见的版本,比如 (1 - 10)

for (int i = 0; i++ < 10;)

或 (1 - 10)

int i = 0;
for (;i++ < 10;)

这表明循环可能比我想象的更可定制。如果我没猜错的话,似乎

  1. 总是需要 2 个分号来分隔 3 个可选语句
  2. 第二个语句需要转换为布尔值 1 才能继续循环
  3. 第一个语句是唯一一个我可以声明变量的语句并且被调用一次
  4. 第三条和第二条语句在每次迭代后调用,可以包含任何内容(声明除外)
  5. 只要满足这些条件,我可以做任何事情

例如 (0, 3, 7)

for (int i = 0, j = 2; i < 10; i+=++j)

这些类型的 for 循环是否被视为该语言的标准用法?或者只是由于 msvc++ 中的实现设计而发生的事情?有关于 for 循环规则的官方说明吗?

你是对的。然而...

仅仅因为有可能并不意味着您应该这样做。 "for" 循环的全部目的是它应该以任何有能力的程序员都能快速理解的级别进行组织。一个关键的基础是程序员应该知道 "for" 循环将 运行 持续多长时间。如果你给所教的内容增加更多的复杂性,那么 "for" 循环的重点就丢失了。我无法轻易地查看您的第三个示例并判断循环将迭代多长时间。

如果您需要像第 3 个示例那样使用 "for" 循环,最好编写一个 while/do-while 循环。

我个人的最爱之一是迭代链表:

for(Node *p = head; p; p = p->next)  ... 

当然,如果你这样做 "no condition",你会得到一个无限循环:

for(;;) ... 

但是是的,只要您有 for( 后跟有效语句、两个分号和 ),它就是 "good code"。

for(printf("h"); !printf("world\n"); printf("ello, "));

是有效的,但 C 代码(和 C++,但 cout 是首选)。

当然,"it compiles and does what you expect" 并不能使它正确或很好地使用该语言。如果其他人可以阅读代码并理解其含义,并且不想去其他地方工作或对最初编写代码的人实施暴力,通常是首选。

来自 ISO C99 草案:

for ( clause-1 ; expression-2 ; expression-3 ) statement behaves as follows:

The expression expression-2 is the controlling expression that is evaluated before each execution of the loop body.

The expression expression-3 is evaluated as a void expression after each execution of the loop body.

If clause-1 is a declaration, the scope of any identifiers it declares is the remainder of the declaration and the entire loop, including the other two expressions; it is reached in the order of execution before the first evaluation of the controlling expression.

If clause-1 is an expression, it is evaluated as a void expression before the first evaluation of the controlling expression.

Both clause-1 and expression-3 can be omitted. An omitted expression-2 is replaced by a nonzero constant.

回答您的问题:

  1. 总是需要2个分号来分隔3个可选语句

    是的。

  2. 第二个语句需要转换为布尔值 1 才能继续循环。

    是的。第二条语句将评估为布尔值 true/false(尽管不一定是“1”)。

  3. 第一个语句是我唯一可以声明变量的语句并且被调用一次

    对于 C++,是的。在 C(C99 之前)中,您必须在 for 循环之外声明变量。

  4. 第三条和第二条语句在每次迭代后调用,可以包含任何内容(声明除外)

    是的。它们可能什么也没有。例如,for ( ;; ) 表示 "loop forever"。 只要满足这些条件,我可以做任何事情

这里有一个很好的教程:

这取决于你想怎么做。 C++ 很灵活,允许您根据需要构建语句。当然,更清晰的方式更可取。

"for" 语句有 3 个部分,用“;”分隔字符:

1) 初始化代码 (int i = 0):在其中初始化要在循环中使用的计数器变量;

2) condition for loop (i < 20): 将测试循环继续的条件;

3)step(increment):可以选择性的给counter变量指定一个增量;

当您知道要迭代(循环)多少次时,"for" 语句具有更可取的用途。否则,建议使用"while".

C++ 的灵活性示例:

for(int i = 0; i < 20; i++) { }

相当于

int i = 0;    
for(;i < 20;) { i++; }