我无法理解 for 循环块和 if 语句

I have trouble understanding about blocks of for loop and if statement

在C Primer Plus中,作者说

A C99 feature, mentioned earlier, is that statements that are part of a loop or if statement qualify as a block even if braces (that is, { } ) aren’t used. More completely, an entire loop is a sub-block to the block containing it, and the loop body is a sub-block to the entire loop block.

我猜 循环体 表示下面示例中的 printf(...) 语句。但是这两个粗体字是什么意思呢? :“.. 整个循环 是包含它的 的子块,...” 如果你能解释一下就好了它使用下面的例子!

for(int n =1;n<3;n++)
    printf("%d \n",n);

表达的有点烂,但是很简单:

for(int n =1;n<3;n++)      // <-- loop
    printf("%d \n",n);     // <-- block

在这种情况下,循环体就像你所说的 printf(),一般来说,尽量让我的答案尽可能少,这是格式:

for(...; ....;)
    body_of_loop

当您有嵌套循环或 if 语句时,sub 就会发挥作用。例如,一个双 for 循环:

1. for(int i = 0; i < 10; ++i)         
2.    for(int j = 0; j < 10; ++j)    
3.        printf("hi\n");

More completely, an entire loop is a sub-block to the block containing it, and the loop body is a sub-block to the entire loop block.

因此,第 2 行是一个 整个循环 并且它是 的子块,它是其中的一部分。外部for循环的块是第2行和第3行。

如果你有一个代码块,例如:

while(1)                 <-- code block (contains if [that contains printf])
    if(2)                <-- sub block (contains printf)
       printf("3");      <--- part of if block

printf 被认为是 if 块的一部分,而 if 块本身(现在也包含 printf)被认为是更大的 while 块的一部分。这可以继续下去......

while(1)
  while(2)
    if(3)
      for(;;)
        i++;

这里的 3 条中线中的每一条都是包含以下几行的子块

C11 标准说,在 §6.8.5 迭代语句

¶5 An iteration statement is a block whose scope is a strict subset of the scope of its enclosing block. The loop body is also a block whose scope is a strict subset of the scope of the iteration statement.

我认为这就是你引用的声明试图解释的内容。

这有点不透明(欢迎来到阅读标准的世界)的目的是迭代语句(while 循环、do … while 循环或 for 循环)被视为一个块。这主要影响带有变量声明的 for 循环。

考虑:

for (int i = 0; i < max; i++)
    printf(" %d", i);
putchar('\n');

措辞意味着代码的功能就像您拥有:

{
    for (int i = 0; i < max; i++)
    {
        printf(" %d", i);
    }
}
putchar('\n');

这特别将i的范围限制在for循环;它在循环外是不可访问的。循环体是一个块,其范围是迭代语句的严格子集,这不足为奇。周围的街区不太明显,可能会让人大吃一惊。