34_综合实例

本文介绍了C++中全局变量与局部变量的概念及其作用范围,通过示例代码展示了全局变量和局部变量(包括重名情况)如何在不同函数中被使用。

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

//_34_综合实例
//_34_main.cpp

//同函数一样,外部变量的定义和外部函数的说明不同
//外部变量的定义只有一词,它的位置必须在所有函数之外
//而同一文件中的外部变量的说明可以有很多次,位置实在函数之内
//(那个函数要用到就在哪个函数中声明)

#include <stdio.h>
#include <stdlib.h>
//声明三个子函数
void head1();
void head2();
void head3();
int count=10;//全局变量

int main()
{
	register int index;//定义为主函数寄存器变量
	//在调用变量index时会节省很多时间
	
	head1();
	head2();
	head3();
	printf("the value of count is:%d\n",count);
	for(index=8;index>0;index--)
	{
		int staff;//局部变量
		//staff的可见范围只在当前函数体内

		for(staff=0;staff<=6;staff++)
			printf("%d ",staff);
		printf("index is now %d\n",index);
	}

	system("pause");
	return 0;
}

int counter;//全局变量,可见范围是从定义之处到源程序结尾

//三个子函数的的定义
void head1()
{
	int index;//局部变量
	index = 23;
	printf("the head1 value(index) is %d\n",index);
}
void head2()
{
	int count;//head2()的局部变量count,
                  //变量名与全局变量重名,
	              //故全局变量count不能呢挂在函数head2中使用
	count = 53;
	printf("the head2 value(count) is %d\n",count);
	counter = 77;
}
void head3()
{
	printf("the head3 value(counter) is %d\n",counter);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值