I come, I see, I conquer

                    —Gaius Julius Caesar

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
  15 随笔 :: 339 文章 :: 128 评论 :: 146万 阅读
< 2025年6月 >
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 1 2 3 4 5
6 7 8 9 10 11 12
复制代码
/* 变量作用域举例 */
#include 
<stdio.h>

void a (void);   /* 函数原型 */
void b (void);   /* 函数原型 */
void c (void);   /* 函数原型 */

int x = 1;       /* 全局变量 */

main()
{
    
int x = 5;   /* main函数的局部变量 */

    printf(
"local x in outer scope of main is %d \n", x);
    
    {
        
int x = 7;   /* 变量x的新作用域 */
        printf(
"local x in inner scope of main is %d \n", x);
    }   
/* 结束变量x的新作用域 */

    printf(
"local x in outer scope of main is %d \n", x);

    a();       
/* 函数a拥有自动局部变量x */
    b();       
/* 函数b拥有静态局部变量x */
    c();       
/* 函数c使用全局变量 */
    a();       
/* 函数a对自动局部变量x重新初始化 */
    b();       
/* 静态局部变量x保持了其以前的值 */
    c();       
/* 全局变量x也保持其值 */

    printf(
"local x in main is %d \n\n", x);

    
return 0;
}

void a(void)
{
    
int x = 25;     /* 每次调用函数a时都会对变量x初始化 */

    printf(
"\nlocal x in a is %d after entering a \n", x);
    
++x;
    printf(
"local x in a is %d before exiting a \n", x);
}

void b(void)
{
    
static int x = 50;    /* 只在首次调用函数b时对静态变量x初始化 */

    printf(
"\nlocal static x is %d on entering b \n", x);
    
++x;
    printf(
"local static x is %d on exiting b \n", x);
}

void c(void)
{
    printf(
"\nglobal x is %d on entering c \n", x);
    x 
*= 10;
    printf(
"global x is %d on exiting c \n", x);
}
复制代码

 

输出:

local x in outer scope of main is 5
local x in inner scope of main is 7
local x in outer scope of main is 5

local x in a is 25 after entering a
local x in a is 26 before exiting a

local static x is 50 on entering b
local static x is 51 on exiting b

global x is 1 on entering c
global x is 10 on exiting c

local x in a is 25 after entering a
local x in a is 26 before exiting a

local static x is 51 on entering b
local static x is 52 on exiting b

global x is 10 on entering c
global x is 100 on exiting c
local x in main is 5

posted on 2008-09-15 20:43  jcsu  阅读(281)  评论(0)    收藏  举报
点击右上角即可分享
微信分享提示