块示例

以下程序显示了数据对象的值在嵌套块中的更改方式:

 /**
  ** 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);
   }
程序将生成以下输出:
second x =    2
first  x =    1

main中定义了两个名为 x 的变量。 x 的第一个定义在 main 运行时保留存储器。 但是,由于 x 的第二个定义发生在嵌套块中,因此 printf("second x = %4d\n", x); 会将 x 识别为上一行中定义的变量。 由于 printf("first x = %4d\n", x); 不是嵌套块的一部分,因此 x 可识别为 x的第一个定义。