static 변수는 사라지지 않고 계속 메모리 내에 저장되어 있습니다.
(메모리 내에 저장되어 있다는 뜻 = 프로그램이 끝날 때까지 있다는 것)
static int count = 0;이런 식으로 자료형 앞에 작성
첫번째 성질: static 변수는 함수내에 선언해도 사라지지 않음!
#include <stdio.h>
void compare_variables() {
int local_var = 0;
static int static_var = 0;
local_var++;
static_var++;
printf("일반:%d, static: %d\n", local_var, static_var);
}
int main() {
printf("첫 번째 호출:\n");
compare_variables();
//일반:1, static: 1
printf("두 번째 호출:\n");
compare_variables();
//일반:1, static: 2
printf("세 번째 호출:\n");
compare_variables();
//일반:1, static: 3
return 0;
}즉 일반 local_var는 함수가 끝남과 동시에 다시 0으로 초기화 되는데 static 변수는 그 값을 계~속 유지하기 때문에 1>2>3 이런식으로 증가됨.
그럼 static 값은 변경하지 못하나요? >> 할 수 있긔,,
#include <stdio.h>
void initialize() {
static int initialized = 0;
//c에서 0은 거짓 1은 참이기 때문에
if (!initialized) { //initialized가 0이면 이라는 뜻
printf("초기화...\n");
initialized = 1;
} else {
printf("초기화 완료되었습니다.\n");
}
}
int main() {
initialize(); //초기화...
initialize(); //초기화 완료되었습니다.
return 0;
}*** initialize 함수 처음에 다시 0으로 되어있는데
왜 두번째 호출에서 자동으로 1이 되어 “초기화 완료 ~”가 뜰까?
>>> static 변수는 한번 초기화 하면 그다음부턴 초기화 X
두번째 성질: 변수를 선언만 하고, 값을 할당하지 않았어도 자동으로 0이 들어가 있음
#include <stdio.h>
void use_static_variable() {
static int static_var; //선언만 된 상태
printf("static_var = %d\n", static_var);
static_var++;
}
int main() {
use_static_variable(); //static_var = 0
use_static_variable(); //static_var = 1
use_static_variable(); //static_var = 2
return 0;
}앞에 char 형태든, int 형태든 모두 0으로 초기화 되어있다람쥐.
Share article