这个静态变量在这个递归的senerio中的作用是什么?

时间:2016-01-30 00:36:32

标签: c recursion static-variables

在我的代码中,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);
    }
}

1 个答案:

答案 0 :(得分:1)

  

我担心的是每次递归调用static variable1;正在   声明。

是的,它是安全的,因为静态存储持续时间的变量不会再次重新声明。它的生命周期是程序的完整执行,并且只在之前初始化一次。因此,除非您打算“重置” if(numberofTimesCalled == 0){ // assuming you intended to check with ==, // a single = is for assignment. variable1 = 0; } 的值,否则您甚至不需要特殊值 条件:

def quiz(question,answer, score):
    import time
    a = raw_input(question)
    if a.lower() == answer.lower():
        score = score + 1
        if score == 1:
            print("correct! So far your score is an awesome " + str(score) + "     point")
            time.sleep(0.5)
        else:
            print("correct! So far your score is an awesome " + str(score) + " points")
            time.sleep(0.5)
    else:
        print("wrong, dumbass! The correct answer was " + answer + "! So far your score is an abysmal " + str(score) + " points")
        time.sleep(0.5)

    return score

question_answer = list()
question_answer.append(["what is my favourite colour? ", "green"])
question_answer.append(["What is my favourite game? ", "cards against humanity"])
question_answer.append(["Who's better: Gandalf or Dumbledore? ", "Gandalf"])

actual_score = 0 

for item in question_answer:
    actual_score = quiz(*[value for value in item], actual_score)

因为具有静态持续时间的变量在程序启动时将初始化为零。