C++入门经典-例4.7-变量的作用域

1:代码如下:

// 4.7.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
using namespace std;
int globalCount = 33;            //全局变量,全局变量的作用域为整个cpp文件
int GetCount();          //声明函数
void SetCount(int k);
void main()
{
    int count = 100;        //局部变量
    cout << globalCount<< endl;//输出全局变量
    SetCount(200);//
    cout << GetCount() << endl;
}

void SetCount(int k)   //定义函数
{
    int hisCount;   //定义局部变量
    //myCount =200;  执行会出错,注释掉
    //count =200;      执行会出错, 注释掉
    hisCount = k; //函数体自身内部定义的变量可以被使用,k也可以看作是局部变量
    globalCount=hisCount;        //给全局变量赋值
    
}
int GetCount()
{
    int myCount; //定义局部变量
    myCount = globalCount;//使用自身的局部变量
    return myCount;
}
View Code

运行结果:

posted @ 2017-09-14 13:59  一串字符串  阅读(157)  评论(0编辑  收藏  举报