C 함수 내부의 정적 변수
무엇을 인쇄합니까? 6 6 또는 6 7? 그리고 왜?
void foo()
{
static int x = 5;
x++;
printf("%d", x);
}
int main()
{
foo();
foo();
return 0;
}
여기에는 수명과 범위라는 두 가지 문제가 있습니다.
변수의 범위는 변수 이름을 볼 수있는 곳입니다. 여기서 x는 foo () 함수 내에서만 볼 수 있습니다.
변수의 수명은 변수가 존재하는 기간입니다. x가 static 키워드없이 정의 된 경우 수명은 foo ()에 대한 항목에서 foo ()의 반환까지입니다. 따라서 모든 호출에서 5로 다시 초기화됩니다.
static 키워드는 변수의 수명을 프로그램의 수명으로 연장하는 역할을합니다. 예를 들어 초기화는 한 번만 발생하고 변수는 foo ()에 대한 모든 향후 호출에 대해 값을 유지합니다.
출력 : 6 7
이유 : 정적 변수는 자동 변수와 달리 한 번만 초기화되며 정적 변수의 추가 정의는 런타임 중에 무시됩니다. 수동으로 초기화하지 않으면 자동으로 0 값으로 초기화됩니다. 그래서,
void foo() {
static int x = 5; // assigns value of 5 only once
x++;
printf("%d", x);
}
int main() {
foo(); // x = 6
foo(); // x = 7
return 0;
}
6 7
컴파일러는 함수가 입력 될 때마다 정적 변수 초기화가 발생하지 않도록 배열합니다.
다음 프로그램이있는 것과 같습니다.
static int x = 5;
void foo()
{
x++;
printf("%d", x);
}
int main()
{
foo();
foo();
return 0;
}
이 프로그램에서 static 키워드가하는 일은 컴파일러에게 (본질적으로) '이봐, 다른 사람이 액세스하지 않기를 바라는 변수가 있습니다. 다른 사람에게 그것이 존재한다고 말하지 마십시오'라고 말하는 것입니다.
메서드 내에서 static 키워드는 컴파일러에게 위와 동일하지만 '이 함수 외부에 존재한다고 아무에게도 말하지 말고이 함수 내에서만 액세스 할 수 있어야합니다'라고 말합니다.
이게 도움이 되길 바란다
A static variable inside a function has a lifespan as long as your program runs. It won't be allocated every time your function is called and deallocated when your function returns.
Output: 6,7
Reason
The declaration of x
is inside foo
but the x=5
initialization takes place outside of foo
!
What we need to understand here is that
static int x = 5;
is not the same as
static int x;
x = 5;
Other answers have used the important words here, scope and lifetime, and pointed out that the scope of x
is from the point of its declaration in the function foo
to the end of the function foo
. For example I checked by moving the declaration to the end of the function, and that makes x
undeclared at the x++;
statement.
So the static int x
(scope) part of the statement actually applies where you read it, somewhere INSIDE the function and only from there onwards, not above it inside the function.
However the x = 5
(lifetime) part of the statement is initialization of the variable and happening OUTSIDE of the function as part of the program loading. Variable x
is born with a value of 5
when the program loads.
I read this in one of the comments: "Also, this doesn't address the really confusing part, which is the fact that the initializer is skipped on subsequent calls." It is skipped on all calls. Initialization of the variable is outside of the function code proper.
The value of 5 is theoretically set regardless of whether or not foo is called at all, although a compiler might optimize the function away if you don't call it anywhere. The value of 5 should be in the variable before foo is ever called.
Inside of foo
, the statement static int x = 5;
is unlikely to be generating any code at all.
I found the address x
uses when I put a function foo
into a program of mine, and then (correctly) guessed that the same location would be used if I ran the program again. The partial screen capture below shows that x
has the value 5
even before the first call to foo
.
The output will be 6 7
. A static variable (whether inside a function or not) is initialized exactly once, before any function in that translation unit executes. After that, it retains its value until modified.
Vadiklk,
Why ...? Reason is that static variable is initialized only once, and maintains its value throughout the program. means, you can use static variable between function calls. also it can be used to count "how many times a function is called"
main()
{
static int var = 5;
printf("%d ",var--);
if(var)
main();
}
and answer is 5 4 3 2 1 and not 5 5 5 5 5 5 .... (infinite loop) as you are expecting. again, reason is static variable is initialized once, when next time main() is called it will not be initialize to 5 because it is already initialized in the program.So we can change the value but can not reinitialized. Thats how static variable works.
or you can consider as per storage: static variables are stored on Data Section of a program and variables which are stored in Data Section are initialized once. and before initialization they are kept in BSS section.
In turn Auto(local) variables are stored on Stack and all the variables on stack reinitialized all time when function is called as new FAR(function activation record) is created for that.
okay for more understanding, do the above example without "static" and let you know what will be the output. That make you to understand the difference between these two.
Thanks Javed
Let's just read the Wikipedia article on Static Variables...
Static local variables: variables declared as static inside a function are statically allocated while having the same scope as automatic local variables. Hence whatever values the function puts into its static local variables during one call will still be present when the function is called again.
You will get 6 7 printed as, as is easily tested, and here's the reason: When foo
is first called, the static variable x is initialized to 5. Then it is incremented to 6 and printed.
Now for the next call to foo
. The program skips the static variable initialization, and instead uses the value 6 which was assigned to x the last time around. The execution proceeds as normal, giving you the value 7.
6 7
x is a global variable that is visible only from foo(). 5 is its initial value, as stored in the .data section of the code. Any subsequent modification overwrite previous value. There is no assignment code generated in the function body.
6 and 7 Because static variable intialise only once, So 5++ becomes 6 at 1st call 6++ becomes 7 at 2nd call Note-when 2nd call occurs it takes x value is 6 instead of 5 because x is static variable.
In C++11 at least, when the expression used to initialize a local static variable is not a 'constexpr' (cannot be evaluated by the compiler), then initialization must happen during the first call to the function. The simplest example is to directly use a parameter to intialize the local static variable. Thus the compiler must emit code to guess whether the call is the first one or not, which in turn requires a local boolean variable. I've compiled such example and checked this is true by seeing the assembly code. The example can be like this:
void f( int p )
{
static const int first_p = p ;
cout << "first p == " << p << endl ;
}
void main()
{
f(1); f(2); f(3);
}
of course, when the expresion is 'constexpr', then this is not required and the variable can be initialized on program load by using a value stored by the compiler in the output assembly code.
참고URL : https://stackoverflow.com/questions/5033627/static-variable-inside-of-a-function-in-c
'programing tip' 카테고리의 다른 글
전체 S3 버킷에 대한 캐시 제어를 자동으로 설정 (버킷 정책 사용?) (0) | 2020.08.16 |
---|---|
이 'for'루프가 중지되고 왜 / 왜 안됩니까? (0) | 2020.08.16 |
Java에 Null OutputStream이 있습니까? (0) | 2020.08.16 |
하위 도메인없이 유효한 도메인 이름과 일치하는 정규 표현식은 무엇입니까? (0) | 2020.08.16 |
ASP.NET MVC 성능 (0) | 2020.08.16 |