static 키워드는 오직 한 함수에서만 볼 수 있는 변수를 만들 때 쓴다. 그러나 함수가 불릴 때마다 만들어졌다 사라지는 지역 변수와 달리 static 변수는 함수 호출을 넘어 계속되며, 함수 호출 사이에 자료를 보존한다.
static 으로 선언된 변수는 함수가 처음 불릴 때 한 번만 만들어지고 초기화된다.
예제 코드
/* 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;
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; // variable to store value in random walk - static 으로 선언되어서
// 다른 함수가 그 값을 바꿀 수 없음
place = place + (random(-moveSize, moveSize + 1));
if (place < randomWalkLowRange) { // 위와 아래 한계 체크
place = randomWalkLowRange + (randomWalkLowRange - place); // 양의 방향에서 뒤로 가는 것을 반영
}
else if (place > randomWalkHighRange) {
place = randomWalkHighRange - (place - randomWalkHighRange); // 양의 방향에서 뒤로 가는 것을 반영
}
return place;
}
더 볼 것
Title
Arduino Newsletter
We care about the privacy and personal data of our users.
To continue, please give us your consent:
Please confirm that you have read the privacy policy
Thank you for subscribing!
Curious to learn more?
Are you also a teacher, student, or professional that loves using Arduino in your day-to-day activities?
Then keep up-to-date with either our STEM or Professional monthly newsletters.
Arduino weekly newsletter (already subscribed)
Educators can benefit from the ever growing tech that shapes our environment through fun cool projects.
Why not awe your boss with highly innovative ways to help keep your enterprise connected at no extra cost?
Arduino Survey
We'd like to get to know you little better.
Please help us improve by answering this super short optional survey.