xy3*_*y36 2 c static global global-variables
假设我有一个函数,并且我使用该函数内部的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()
?