变量作用域[c][code]

本文通过一个C语言程序实例详细解析了变量作用域的概念,包括全局变量、局部变量、静态局部变量的不同作用范围及其生命周期特点。演示了如何在不同函数中使用相同名称但不同作用域的变量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/* 变量作用域举例 */
#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

转载于:https://www.cnblogs.com/JCSU/articles/1291237.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值