static

名称

static

説明

関数の中で宣言される変数を、staticを使って宣言すると、自動変数と同様に、その関数の中からだけ参照可能な変数を作成する。staticを使って宣言された変数は、ローカル変数とは異なり、静的記憶域期間を持つ。すなわち、関数が呼ばれるたびに生成され、関数が終了するときに削除される自動変数とは異なり、static変数は、関数が終了した後も、その値は保持され続ける。

staticと宣言された変数は、関数が最初に呼ばれるときに、一度だけ生成され、初期化される。

使用例

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/* RandomWalk
  Paul Badger 2007
  RandomWalk wanders up and down randomly between two
  endpoints. The maximum move in one loop is governed by
  the parameter "stepsize".
  A static variable is moved up and down a random amount.
  This technique is also known as "pink noise" and "drunken walk".
*/

#define randomWalkLowRange -20
#define randomWalkHighRange 20
int stepsize;

int thisTime;

void setup() {
  Serial.begin(9600);
}

void loop() {
  //  test randomWalk function
  stepsize = 5;
  thisTime = randomWalk(stepsize);
  Serial.println(thisTime);
  delay(10);
}

int randomWalk(int moveSize) {
  static int place; // variable to store value in random walk - declared static so that it stores
  // values in between function calls, but no other functions can change its value

  place = place + (random(-moveSize, moveSize + 1));

  if (place < randomWalkLowRange) {                               // check lower and upper limits
    place = randomWalkLowRange + (randomWalkLowRange - place);    // reflect number back in positive direction
  }
  else if (place > randomWalkHighRange) {
    place = randomWalkHighRange - (place - randomWalkHighRange);  // reflect number back in negative direction
  }

  return place;
}

参照

オリジナルのページ

https://www.arduino.cc/reference/en/language/variables/variable-scope-qualifiers/static/

Last Revision: 2019/02/21

最終更新日

January 4, 2024

inserted by FC2 system