C++的作用域问题

来源:百度知道 编辑:UC知道 时间:2024/05/25 07:48:55
一本教课书上的程序,如下

#include <iostream>
using std::cout;
using std::endl;

void useGlobal( void ); // function prototype

int x = 1; // global variable

int main()
{
int x = 5; // local variable to main

useGlobal(); // useGlobal uses global x
useGlobal(); // global x also retains its value

cout << "\nlocal x in main is " << x << endl;
return 0; // indicates successful termination
} // end main

// useGlobal modifies global variable x during each call
void useGlobal( void )
{
cout << "\nglobal x is " << x << " on entering useGlobal" << endl;
x *= 10;
cout << "global x is " << x << " on exiting useGlobal" << endl;
} // end function useGlobal

输出的数字部分按顺序为: 1 10 10 100 5

请问use

int x = 1; // global variable

int main()
{
int x = 5; // local variable to main

这两个是不同的变量.

因为函数void useGlobal( void ); 是这样申明的,所以useGlobal不能使用main函数内的局部变量,如果把函数申明成
void useGlobal( int x );
调用的时候useGlobal(x)的话,x的值就是5了

离开主函数后,主函数中的x就不存在了,此时只有全局变量x是可见的(int x=1;),在useGlobal()函数中的x就是这个全局变量x而不是主函数中的x