Jin Jin - 3 months ago 12
C Question

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

In C Primer Plus, the author says that


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.


I guess the loop body means the
printf(...)
statement in the example below. But what do these these two bold words mean? : ".. an entire loop is a sub-block to the block containing it,..." It would be nice if you could explain it using the example below!

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

Answer

The C11 standard says, in §6.8.5 Iteration statements

¶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.

I think this is what the statement you quote is attempting to paraphrase.

What this is driving at, somewhat opaquely (welcome to the world of reading standards), is that an iteration statement (while loop, do … while loop or for loop) is treated as a block. This primarily affects the for loop with variable declarations.

Consider:

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

The wording means that the code functions as if you had:

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

This particularly limits the scope of i to the for loop; it is not accessible outside the loop. The loop body being a block whose scope is a strict subset of the iteration statement isn't a big surprise. The surrounding block is less obvious and could be a surprise.

Comments