#include <iostream>
using namespace std;
void anotherFunction() ; // Function prototype
int main()
{
int num = 1; // Local variable
cout << "In main, num is " << num << endl;
anotherFunction();
cout << "Back in main, num is still " << num << endl;
return 0;
}
void anotherFunction()
{
int num = 20; // Local variable
cout << "In anotherFunction, num is " << num << endl;
}
程序输出结果:
In main, num is 1
In anotherFunctionr, num is 20
Back in main, num is still 1
int sum(int num1, int num2)
{
int result = num1 + num2;
return result;
}
#include <iostream>
using namespace std;
void anotherFunction(); // Function prototype
int num = 2; // Global variable
int main()
{
cout << "In main, num is " << num << endl;
anotherFunction();
cout << "Back in main, num is " << num << endl;
return 0;
}
void anotherFunction ()
{
cout << "In anotherFunction, num is " << num << endl;
num = 50;
cout << "But, it is now changed to " << num << endl;
}
程序输出结果:
In main, num is 2
In anotherFunction, num is 2
But, it is now changed to 50
Back in main, num is 50
//This program has an uninitialized global variable.
#include <iostream>
using namespace std;
int globalNum; // Global variable automatically set to zero
int main()
{
cout << "globalNum is " << globalNum << endl;
return 0;
}
程序输出结果:
globalNum is 0
注意,局部变量不会像全局变量那样自动初始化,程序员必须对它进行处理。虽然全局变量可以很有用,但是应该限制对它们的使用。
#include <iostream>
using namespace std;
void California (); // Function prototype
const int BIRDS = 500; // Global constant
int main()
{
cout << "In main there are " << BIRDS << " birds.\n";
California();
return 0;
}
void California()
{
const int BIRDS = 10000;
cout << "In California there are " << BIRDS << " birds.\n";
}
程序输出结果:
In main there are 500 birds.
In California there are 10000 birds.
版权说明:Copyright © 广州松河信息科技有限公司 2005-2025 版权所有 粤ICP备16019765号
广州松河信息科技有限公司 版权所有