涉及静态局部变量的递归函数中的意外输出

时间:2018-08-21 20:34:10

标签: c function recursion

我正在尝试查找fun(5)的输出。但是我得到了意外的结果(19),不知道为什么。
我的疑问是,例如对于n = 5,它将返回fun(3)+3。之后,返回fun(4)+ x会起作用,还是会再次调用fun函数?

int fun(int n)
{
   static int x = 0;
   if (n<=0) return 1;
   if (n>3)
   {
     x = n;
     return fun(n-2) + 3;
   }
   return fun(n-1) + x;
}

1 个答案:

答案 0 :(得分:3)

这是发生的事情的顺序:

call fun(5)
  x=0; which, being the initialisation of a static local variable, 
       only happens before the very first call to fun()
  5>3: x=5 (not a problem, static vars can be changed and keep the value)
  return fun(3)+3
    return fun(2) + 5
      return fun(1) + 5
        return fun(0) + 5
          return 1
        return 1 + 5
      return 6 + 5
    return 11 + 5
  return 16 + 3

以下几行之间的关系的确切含义似乎使您感兴趣。

static int x = 0;
/* Defines a local but static variable, initialised to 0;
   the initialisation happens before the first execution of the function,
   conceptually at the beginning of the whole program (credits John Bollinger).
   This does NOT cause an assignment to 0 during each execution of the function.
   The static attribute also means that the value at the end of one
   execution will still be found in the variable at the start of the next
   execution, even and especially if that start is before the end of the current execution,
   which is typical for recursive functions.
 */

/* ... */

x = n;
/* This conditional (inside an if) assignment in the middle of the 
   recursive function changes the value of the static variable away from
   the initialisation value, to e.g. 5.
   If/because no other assignment occurs, the value will stay in the
   for the rest of the program.
 */