Example of blocks

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

 /**
  ** This example shows how data objects change in nested blocks.
  **/
   #include <stdio.h>

   int main(void)
   {
      int x = 1;                     /* Initialize x to 1  */
      int y = 3;

      if (y > 0)
      {
         int x = 2;                  /* Initialize x to 2  */
         printf("second x = %4d\n", x);
      }
      printf("first  x = %4d\n", x);

      return(0);
   }

The program produces the following output:

second x =    2
first  x =    1

Two variables named x are defined in main. The first definition of x retains storage while main is running. However, because the second definition of x occurs within a nested block, printf("second x = %4d\n", x); recognizes x as the variable defined on the previous line. Because printf("first x = %4d\n", x); is not part of the nested block, x is recognized as the first definition of x.