6.10 Static local variables

주홍영·2022년 3월 12일
0

Learncpp.com

목록 보기
69/199

https://www.learncpp.com/cpp-tutorial/static-local-variables/

Static 이라는 용어는 c++에서 가장 혼란스러운 용어중 하나이다
왜냐하면 상황에 따라 그 의미가 매번 바뀌기 때문이다

이전 섹션에서 global variables의 static duration에 대해서 이야기했다
이는 프로그램이 시작되고 끝날때까지 유효하다는 의미를 뜻한다

또한 global identifier에 static 키워드를 쓰면 internal linkage가 되고
이말은 오직 define된 파일 내부에서만 사용가능하다는 의미였다

이번 섹션에서는 local variable에 static keyword가 쓰였을 때에 대해서 살펴본다

Static local variables

Using the static keyword on a local variable changes its duration from automatic duration to static duration. This means the variable is now created at the start of the program, and destroyed at the end of the program (just like a global variable). As a result, the static variable will retain its value even after it goes out of scope!
핵심은 out of scope 상황에서도 value를 retain (유지하다) 한다는 것이다

#include <iostream>

void incrementAndPrint()
{
    static int s_value{ 1 }; // static duration via static keyword.  This initializer is only executed once.
    ++s_value;
    std::cout << s_value << '\n';
} // s_value is not destroyed here, but becomes inaccessible because it goes out of scope

int main()
{
    incrementAndPrint();
    incrementAndPrint();
    incrementAndPrint();

    return 0;
}

static으로 선언되었으므로 매 실행마다 값이 유지되어
출력은 다음과 같아진다

2
3
4

profile
청룡동거주민

0개의 댓글