정적 변수

(정적변수에서 넘어옴)

컴퓨터 프로그래밍에서 정적 변수(靜的變數, static variable)는 정적으로 할당되는 변수이며, 프로그램 실행 전반에 걸쳐 변수의 수명이 유지된다.

기억 장소가 콜 스택에서 할당 및 할당 해제되는, 수명이 더 짧은 자동 변수(지역 변수가 일반적으로 자동임)와는 반대되는 개념이다. 즉, 기억 장소가 힙 메모리동적 할당되는 객체와 반의어이다. 정적 메모리 할당은 일반적으로 관련 프로그램을 실행하기 앞서 컴파일 시간에 메모리를 할당하는 것을 일컬으며 이는 메모리가 런타임 중에 필요할 때 할당되는 동적 메모리 할당이나 자동 메모리 할당과는 다르다.[1]

C 및 관련 언어에서는 정적 변수와 기타 개념들 모두 static 키워드가 사용된다.

범위 편집

편집

아래는 C에서의 정적 지역 변수의 예이다.

#include <stdio.h>

void func() {
	static int x = 0;
	/* x는 func()가 5번 호출될 동안 단 한번 초기화되었고,
	변수는 함수가 호출되는 동안 총 5번 증가한다.
	x의 최종적인 값은 5이다. */
	x++;
	printf("%d\n", x); // x 값을 출력한다
}

int main() { // main 안의 int argc, char *argv[]는 특정 프로그램에서는 선택 사항이다
	func(); // 출력: 1
	func(); // 출력: 2
	func(); // 출력: 3
	func(); // 출력: 4
	func(); // 출력: 5
	return 0;
}

각주 편집

  1. Jack Rons. “What is static memory allocation and dynamic memory allocation?”. http://www.merithub.com/: MeritHub [An Institute of Career Development]. 2011년 5월 19일에 원본 문서에서 보존된 문서. 2011년 6월 16일에 확인함. The compiler allocates required memory space for a declared variable. By using the addressof operator, the reserved address is obtained and this address may be assigned to a pointer variable. Since most of the declared variables have static memory, this way of assigning pointer value to a pointer variable is known as static memory allocation. Memory is assigned during compilation time.