C++全局变量分析

C++中的全局变量,分为静态、有外部链接性的变量和静态、内部链接性的变量。

1. 静态、外部链接性变量

在file1中如下定义:

#include "iostream"
using namespace std;
void printGlobalinFile2();
void printGlobalinFile3();
void printnotGlobalinFile3();
void printnotGlobalinFile4();

int global = 0; //全局、外链性变量
int main()
{
    cout<<global<<" in file1"<<endl;
    printGlobalinFile2();
    printGlobalinFile3();
    printnotGlobalinFile3();
    printnotGlobalinFile4();
}

在file2中定义如下:

#include "iostream"
using namespace std;

extern int global; //引用file1中的global变量
//int global = 1;  //错误
void printGlobalinFile2()
{
    cout<<global<<" in file2"<<endl;
}

2. 静态,内部链接性

在file3中定义如下:

#include "iostream"
using namespace std;
static int global = 1; //加上static关键字后,覆盖file1中的global
static int notGlobal = 2; //内部链接性

void printGlobalinFile3()
{
    cout<<global<<" in file3"<<endl;
}

void printnotGlobalinFile3()
{
    cout<<notGlobal<<" in file3"<<endl;
}

在file4中定义如下:

#include "iostream"
using namespace std;
extern int notGlobal; //错误
static int notGlobal = 3; //ok

void printnotGlobalinFile4()
{
    cout<<notGlobal<<" in file4"<<endl;
}

输出结果为:

0 in file1

0 in file2

1 in file3

2 in file3

3 in file4


PS : 对于未被初始化的外链性的变量,系统默认会为其赋值为0;




  


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值