static

Descrição

A palavra-chave

static
é usada para criar variáveis que são visíveis para apenas uma função. No entanto, diferentemente de variáveis locais, que são criadas e destruidas toda vez que uma função é chamada, variáveis
static
persistem entre chamadas da função, preservando seu valor.

Variáveis declaradas como static são criadas e inicializadas apenas a primeria vez que uma função é chamada.

Código de Exemplo

1/* RandomWalk
2 Paul Badger 2007
3 RandomWalk wanders up and down randomly between two
4 endpoints. The maximum move in one loop is governed by
5 the parameter "stepsize".
6 A static variable is moved up and down a random amount.
7 This technique is also known as "pink noise" and "drunken walk".
8 */
9
10 #define randomWalkLowRange -20
11 #define randomWalkHighRange 20
12 int stepsize;
13
14 int thisTime;
15 int total;
16
17 void setup() {
18 Serial.begin(9600);
19 }
20
21 void loop() {
22 // test randomWalk function
23 stepsize = 5;
24 thisTime = randomWalk(stepsize);
25 Serial.println(thisTime);
26 delay(10);
27 }
28
29 int randomWalk(int moveSize) {
30 static int place; // variable to store value in random walk - declared static so that it stores
31 // values in between function calls, but no other functions can change its value
32
33 place = place + (random(-moveSize, moveSize + 1));
34
35 if (place < randomWalkLowRange) { // check lower and upper limits
36 place = randomWalkLowRange + (randomWalkLowRange - place); // reflect number back in positive direction
37 }
38 else if (place > randomWalkHighRange) {
39 place = randomWalkHighRange - (place - randomWalkHighRange); // reflect number back in negative direction
40 }
41
42 return place;
43 }

Ver também

Suggest changes

The content on docs.arduino.cc is facilitated through a public GitHub repository. If you see anything wrong, you can edit this page here.

License

The Arduino documentation is licensed under the Creative Commons Attribution-Share Alike 4.0 license.