C[复制]中的局部静态变量范围

时间:2021-04-28 16:49:28

This question already has an answer here:

这个问题已经有了答案:

I have a simple question about static variables. If I declared a static variable in a function:

我有一个关于静态变量的简单问题。如果我在函数中声明一个静态变量:

void main()
{
    int k = 0
    while(k<=4)
    {
        fun();
        k++;
    }
}
int fun()
{
    static int i=5;
    i++;
    printf(Value %d\t", i);
    return 0;
}

As I know, the function will deallocate after returning. But where is the i value stored. Is a static variable like a global variable.

正如我所知道的,返回后函数将释放。但是,i值存储在哪里。是一个静态变量,像一个全局变量。

2 个解决方案

#1


2  

The function will not deallocate i inside fun() on return. The storage for i is in the same general area as global variables — but it is not a global variable. It is only accessible inside the function fun() where it is defined. It is separate from any global variable i or any other variable i that is static inside any other function (in any source file), or from a file scope static variable i in the source file where fun() is defined. It has a lifetime as long as the program.

函数不会在返回时释放i内的fun()。我的存储空间与全局变量相同,但它不是一个全局变量。只有在定义它的函数fun()中才能访问它。它是独立于任何全局变量i或任何其他变量i(在任何源文件中),或从文件作用域静态变量i(在源文件中定义了fun())。它的寿命和程序一样长。

#2


1  

As I know, the function will deallocate after returningNo. I think your assumption is wrong!

正如我所知道的,返回后函数将释放- No。我认为你的假设是错误的!

static variables won't be deallocated after returning from the function.

从函数返回后,静态变量不会被释放。

Where is it stored?static variables are stored in "Data Section" or "Data Memory".

它存储在哪里?-静态变量存储在“数据段”或“数据内存”中。

Life — The life of the static variable starts when the program is loaded into RAM, and ends when the program execution finishes!

生命-当程序被加载到RAM中时,静态变量的生命开始,在程序执行结束时结束!

#1


2  

The function will not deallocate i inside fun() on return. The storage for i is in the same general area as global variables — but it is not a global variable. It is only accessible inside the function fun() where it is defined. It is separate from any global variable i or any other variable i that is static inside any other function (in any source file), or from a file scope static variable i in the source file where fun() is defined. It has a lifetime as long as the program.

函数不会在返回时释放i内的fun()。我的存储空间与全局变量相同,但它不是一个全局变量。只有在定义它的函数fun()中才能访问它。它是独立于任何全局变量i或任何其他变量i(在任何源文件中),或从文件作用域静态变量i(在源文件中定义了fun())。它的寿命和程序一样长。

#2


1  

As I know, the function will deallocate after returningNo. I think your assumption is wrong!

正如我所知道的,返回后函数将释放- No。我认为你的假设是错误的!

static variables won't be deallocated after returning from the function.

从函数返回后,静态变量不会被释放。

Where is it stored?static variables are stored in "Data Section" or "Data Memory".

它存储在哪里?-静态变量存储在“数据段”或“数据内存”中。

Life — The life of the static variable starts when the program is loaded into RAM, and ends when the program execution finishes!

生命-当程序被加载到RAM中时,静态变量的生命开始,在程序执行结束时结束!