main : a=1 b=2 block1 : a=1 b=3 block2s: a=1 b=2 block2e: a=4 b=2 main : a=1 b=2
#include <stdio.h> int main( void ) { int a = 1; int b = 2; printf("main : a=%d\tb=%d\n", a, b ); { int b = 3; printf("block1 : a=%d\tb=%d\n", a, b ); } { printf("block2s: a=%d\tb=%d\n", a, b ); int a = 4; printf("block2e: a=%d\tb=%d\n", a, b ); } printf("main : a=%d\tb=%d\n", a, b ); system("pause"); return 0; }
Comments: Each inner block declares a variable that overshadows a variable declared by the main block. However, the scope of those inner variables is limited to the block in which they were declared.
In the second nested block, the variable a
in the
first printf
statement refers to the variable in the outer block.
Then the block declares another variable a
which has a
scope starting at that point.
The
second printf
statement in that block refers to
that new variable.
Question: How many identifiers are in the above program?
There are two identifiers: a
and b
.
Question: How many variables are in the above program?
There are four variables: two int
variables named
a
and b
in the outer scope, an int
variable named b
in the first nested scope, and
an int
variable named a
in the second nested scope.
When a change is made to a variable, no other variable is affected, not even variables with the same name in other scopes.