小编xy3*_*y36的帖子

静态全局变量和函数内部静态变量的区别

假设我有一个函数,并且我使用该函数内部的void func()变量。testVar另外,我需要变量在离开函数后仍然存在。通常我会通过在函数内部使用静态变量来做到这一点(1)。但是,当我使用全局变量时,有什么区别(2)?

static int testVar = 0; //global variable instead(2)

void func()
{
    static int testVar = 0; //static variable inside of the function(1)

    if(testVar++){
        //do something
    }   
}
Run Code Online (Sandbox Code Playgroud)

编译器在这两种情况下具体做了什么?如果仅需要该变量,是否存在应该使用方法(2)的情况func()

c static global global-variables

2
推荐指数
1
解决办法
1842
查看次数

标签 统计

c ×1

global ×1

global-variables ×1

static ×1