For example, we have such code:
#include <stdio.h>
int main(void)
{
int n = 4;
{
n++;
}
printf("%d\n",n);
return 0;
}
How does the inner block see the variable n? How does the C language standard explain this? I've been looking for an answer to this question for quite some time. In my opinion, the answer is as follows: In C17, we have (6.8 #3):
A block allows a set of declarations and statements to be grouped into one syntactic unit. The initializers of objects that have automatic storage duration, and the variable length array declarators of ordinary identifiers with block scope, are evaluated and the values are stored in the objects (including storing an indeterminate value in objects without an initializer) each time the declaration is reached in the order of execution, as if it were a statement, and within each declaration in the order that declarators appear.
If you don't keep initializers in mind, it turns out that a block is just a few statements.We just use a block to evaluate all these operators as one syntactic unit.In other words, if you remove the {} characters in the block, these will be the same operators and the result will be exactly the same, but these operators will not be evaluated in one syntax unit:
#include <stdio.h>
int main(void)
{
int n = 4;
n++; // same effect but without {}
printf("%d\n",n);
return 0;
}
Also we have (6.2.1 # 4):
If the declarator or type specifier that declares the identifier appears inside a block or within the list of parameter declarations in a function definition, the identifier has block scope, which terminates at the end of the associated block.
From this we understand that n has a block scope.
If we combine all of the above, it turns out that n is incremented as if the increment operator never appeared in the inner block.
Is this answer correct? If not, please explain why.And please quote a paragraph from the C language standard.
How does the inner block see the variable
n
?
Because the inner block is part of the outer block (i.e. the function body in this case).
Section 6.2.1p4 of the C standard describes block scope:
If the declarator or type specifier that declares the identifier appears inside a block or within the list of parameter declarations in a function definition, the identifier has block scope, which terminates at the end of the associated block
So the scope of n
is the block which is the body of the main
function. This includes the block containing the n++
statement.
Note that the following which might look more familiar is the same in terms of scope:
int n = 4;
if (n>2) {
n++;
}
In this case, the block is the "statement" part of the if
statement, and as above this block is an "inner" scope to the function body.