05 C语言 static

本文探讨了C++中static关键字的三个主要特性:隐藏性、持久性和默认初始化为0。通过实例展示了static如何限制全局变量的作用域,如何保持局部变量在函数调用间的持久状态,以及未初始化的静态变量默认值为0。

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

#include"head_01.h"

// 01 static 的隐藏性
char a = 'A'; // 全局变量 但如果加了static 只能在本文件使用
void msg()
{
    printf("Hello\n");
}

void static_func_01()
{
    extern char a;    // extern variable must be declared before use
    printf("%c ", a);
    msg();
}


// 02 static 的隐藏性和持久性
int fun(void) {
    static int count = 10;    // 事实上此赋值语句从来没有执行过,如果没有static 每次都会执行赋值,有了static 它只为执行一次赋值
    //int count = 10;    
    return count--;
}

int count = 1;
void static_func_02()
{
    printf("global\t\tlocal static\n");
    for (; count <= 10; ++count)
        printf("%d\t\t%d\n", count, fun());
}

// 03 static 默认值为0
static int z;
int static_func_03()
{
    static char str[10];
    printf("integer: %d;  string: (begin)%s(end)", z, str);// integer: 0;  string: (begin)(end)
    return 0;
}



void main()
{
    static_func_01();
    static_func_02();
    static_func_03();
    system("pause");

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值