Static variable inside of a function in C

2019-01-03 08:48发布

What will be printed out? 6 6 or 6 7? And why?

void foo()
{
    static int x = 5;
    x++;
    printf("%d", x);
}

int main()
{
    foo();
    foo();
    return 0;
}

标签: c static
12条回答
劳资没心,怎么记你
2楼-- · 2019-01-03 09:27

There are two issues here, lifetime and scope.

The scope of variable is where the variable name can be seen. Here, x is visible only inside function foo().

The lifetime of a variable is the period over which it exists. If x were defined without the keyword static, the lifetime would be from the entry into foo() to the return from foo(); so it would be re-initialized to 5 on every call.

The keyword static acts to extend the lifetime of a variable to the lifetime of the programme; e.g. initialization occurs once and once only and then the variable retains its value - whatever it has come to be - over all future calls to foo().

查看更多
贪生不怕死
3楼-- · 2019-01-03 09:29

6 7

compiler arranges that static variable initialization does not happen each time the function is entered

查看更多
Viruses.
4楼-- · 2019-01-03 09:29

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.

查看更多
冷血范
5楼-- · 2019-01-03 09:29

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.

查看更多
一夜七次
6楼-- · 2019-01-03 09:32

Output: 6 7

Reason: static variable is initialised only once (unlike auto variable) and further definition of static variable would be bypassed during runtime. And if it is not initialised manually, it is initialised by value 0 automatically. So,

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;
}
查看更多
小情绪 Triste *
7楼-- · 2019-01-03 09:37

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.

查看更多
登录 后发表回答