全局变量的作用域是从定义点到本文件结束。如果定义点之前的函数需要引用这些外部变量时,需要在函数内对被引用的外部变量进行说明。extern 数据类型 外部变量。
#include<iostream>
using namespace std;//必须得加上
int s1,s2,s3;
int vs(int a,int b,int c)
{
extern int s4;//这里引用了外部变量s4
int v;
v=a*b*c;
s1=a*b;
s2=b*c;
s3=a*c;
s4=a+b+c;
return v;
}
int s4;
int main()
{
int v,l,w,h;
cout<<"Please input length,width and height:"<<endl;
cin>>l>>w>>h;
v=vs(l,w,h);
cout<<"v="<<v<<endl;
cout<<"s1="<<s1<<endl;
cout<<"s2="<<s2<<endl;
cout<<"s3="<<s3<<endl;
cout<<"s4="<<s4<<endl;
}
Please input length,width and height:
10 15 20
v=3000
s1=150
s2=300
s3=200
s4=45 //这里的结果表示s4=45
--------------------------------
Process exited after 4.322 seconds with return value 0
请按任意键继续. . .
int vs(int a,int b,int c)
{
int s4; //定义的局部变量s4
int v;
v=a*b*c;
s1=a*b;
s2=b*c;
s3=a*c;
s4=a+b+c;
return v;
}
但如果不加入extern 而直接定义一个内部变量s4,显示的结果
Please input length,width and height:
10 15 20
v=3000
s1=150
s2=300
s3=200
s4=0
--------------------------------
Process exited after 3.119 seconds with return value 0
请按任意键继续. . .
这里的s4变成了0,也就是没能引用全局变量s4。