繼續看範例fig06_12.cpp下半段,一開始定義三個函式原型void useLocal(), void useStaticLocal(), void useGlobal(), 我稍微修改了一下main(),透過for迴圈各自呼叫三次,可以發現useStaticLocal()與useGlobal()的變數x的值各累加了兩次,但 useLocal()裡x的值並沒有改變。
local x is 100
local static x is 200
global x is 300
local x is 100
local static x is 201
global x is 301
local x is 100
local static x is 202
global x is 302
#include <iostream>
using std::cout;
using std::endl;
void useLocal(); // function prototype
void useStaticLocal(); // function prototype
void useGlobal(); // function prototype
int x = 300; // global variable
int main()
{
for (int i = 0; i <3; i++)
{
useLocal(); // useLocal has local x
useStaticLocal(); // useStaticLocal has static local x
useGlobal(); // global x also retains its value
cout << endl;
}
return 0; // indicates successful termination
} // end main
// useLocal reinitializes local variable x during each call
void useLocal( void )
{
int x = 100; // initialized each time useLocal is called
cout << "\nlocal x is " << x ;
x++;
}
void useStaticLocal( void )
{
static int x = 200; // initialized first time useStaticLocal is called
cout << "\nlocal static x is " << x ;
x++;
}
void useGlobal( void )
{
cout << "\nglobal x is " << x ;
x++;
}