在C静态变量重新分配的每个父函数调用时? [英] Are static variables in C re-allocated every time the parent function is called?

查看:93
本文介绍了在C静态变量重新分配的每个父函数调用时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假如我有在C函数内声明的静态变量。

如果我多次调用该函数,做静态变量得到在内存中的函数被调用时重新分配?

如果它得到重新分配,为什么最后的值始终保持?

例如:

 无效的add()
{
    静态INT X = 1;
    X ++;
    的printf(%d个\\ N,X);
}诠释的main()
{
    加(); //返回2
    加(); //返回3
    加(); //返回4
}


解决方案

没有 - 静态变量基本上都是生活在当地的命名空间中的全局

Suppose I have a static variable declared inside a function in C.

If I call that function multiple times, does the static variable get re-allocated in memory every time the function is called?

If it does get re-allocated, why is the last value always maintained?

Example:

void add()
{
    static int x = 1;
    x++;
    printf("%d\n",x);
}

int main()
{
    add(); // return 2
    add(); // return 3
    add(); // return 4
}

解决方案

No - static variables are basically globals that live within the local namespace.

这篇关于在C静态变量重新分配的每个父函数调用时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆