Static
函式中用 static 宣告的變數只能在該函式中被使用,但它不像一般區域變數,每當函式被呼叫時,就會被重新創建然後隨著函式執行完畢後就會被釋放,靜態變數的存在不受函式的呼叫與否影響,變數的值在每次呼叫完函式之後繼續被保留。
變數只能在第一次呼叫函式時被宣告為靜態變數並給定型別、初值。
範例
/* RandomWalk
* Paul Badger 2007
* RandomWalk 執行一個隨機漫步在兩個端點之間的動作,
* 最大的移動量由loop函式中的參數 ”stepsize” 決定,
* 一個表示位置的靜態變數會被上下移動一個隨機的移動量;
* 這種技術也被稱為 "pink noise" 或 "drunken walk"。
*/
#define randomWalkLowRange -20
#define randomWalkHighRange 20
int stepsize;
int thisTime;
int total;
void setup()
{
Serial.begin(9600);
}
void loop()
{ // 測試randomWalk函式
stepsize = 5;
thisTime = randomWalk(stepsize);
Serial.println(thisTime);
delay(10);
}
int randomWalk(int moveSize){
static int place; // 在 randomWalk 中儲存位置數值的變數
// 宣告為靜態才能在兩次的函式呼叫間保留之前的數值,但該數值卻不會被其他函式修改。
place = place + (random(-moveSize, moveSize + 1));
if (place < randomWalkLowRange){ // 確認位置的最大和最小極限值
place = place + (randomWalkLowRange - place); // 越界後往正方向返回
}
else if(place > randomWalkHighRange){
place = place - (place - randomWalkHighRange); // 越界後往負方向返回
}
return place;
}
本頁由熱血青年 LBU 譯自英文版。
The text of the 86Duino reference is a modification of the Arduino reference, and is licensed under a Creative Commons Attribution-ShareAlike 3.0 License. Code samples in the reference are released into the public domain.
