Example of Initialization within Statement Blocks

The following program shows how the values of data objects change in nested statement blocks:

 1   #include <stdio.h>
 2
 3   int main(void)
 4   {
 5      int x = 1;                 /* Initialize x to 1  */
 6      int y = 3;
 7
 8      if (y > 0)
 9      {
10         int x = 2;              /* Initialize x to 2  */
11         printf("second x = %4d\n", x);
12      }
13      printf("first  x = %4d\n", x);
14   }

The program produces the following output:

second x =    2
first  x =    1

Two variables named x are defined in main. The definition of x on line 5 retains storage while main is running. However, because the definition of x on line 10 occurs within a nested block, line 11 recognizes x as the variable defined on line 10. Because line 13 is not part of the nested block, x is recognized as the variable defined on line 5.



Initializers


Statement Blocks