iT邦幫忙

2021 iThome 鐵人賽

DAY 12
0

繼續看範例fig06_12.cpp下半段,一開始定義三個函式原型void useLocal(), void useStaticLocal(), void useGlobal(), 我稍微修改了一下main(),透過for迴圈各自呼叫三次,可以發現useStaticLocal()與useGlobal()的變數x的值各累加了兩次,但 useLocal()裡x的值並沒有改變。

  • Result
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
  • fig06_12.cpp
#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++; 
} 


上一篇
Days11
下一篇
Day13-stack
系列文
少年DevOps的C++奇怪漂流30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言