在这个递归场景中,这个静态变量的功能是什么?
What this static variable function as expected in this recursive senerio?
在我下面的代码中,variable1
仅在第一次调用时被初始化为 0
。我担心的是,在每个递归调用中都声明了 static variable1;
。这会导致跟踪数字的问题吗?或者编译器是否知道在每个递归调用中跳过声明?
我的代码:
void funtion1(numberOfTimesCalled){
numberOfTimesCalled++;
static variable1;
if(numberofTimesCalled = 0){
variable1 = 0;
}
<some processing>
variable1= variable1+1;
if(variable1<10){
function1(numberOfTimesCalled);
}
}
My concern is that in every recursive call static variable1; is being
declared.
是的,它是安全的,因为具有静态存储持续时间 的变量不会再次重新声明。它的生命周期是整个程序的执行,之前只初始化一次。所以除非你打算 "reset" varaible1
的值,你甚至不需要特殊的
条件:
if(numberofTimesCalled == 0){ // assuming you intended to check with ==,
// a single = is for assignment.
variable1 = 0;
}
因为具有静态持续时间的变量将在程序启动时初始化为零。
在我下面的代码中,variable1
仅在第一次调用时被初始化为 0
。我担心的是,在每个递归调用中都声明了 static variable1;
。这会导致跟踪数字的问题吗?或者编译器是否知道在每个递归调用中跳过声明?
我的代码:
void funtion1(numberOfTimesCalled){
numberOfTimesCalled++;
static variable1;
if(numberofTimesCalled = 0){
variable1 = 0;
}
<some processing>
variable1= variable1+1;
if(variable1<10){
function1(numberOfTimesCalled);
}
}
My concern is that in every recursive call static variable1; is being declared.
是的,它是安全的,因为具有静态存储持续时间 的变量不会再次重新声明。它的生命周期是整个程序的执行,之前只初始化一次。所以除非你打算 "reset" varaible1
的值,你甚至不需要特殊的
条件:
if(numberofTimesCalled == 0){ // assuming you intended to check with ==,
// a single = is for assignment.
variable1 = 0;
}
因为具有静态持续时间的变量将在程序启动时初始化为零。