使用静态变量的递归调用上的不同输出

问题描述 投票:-4回答:3
int fun1(int x){
    static int n;
    n = 0;
    if(x > 0){
        n++;
        return fun1(x-1)+n;
    }
    return 0;
}
int fun(int x){
    static int n = 0;
    if(x > 0){
        n++;
        return fun(x-1)+n;
    }
    return 0;
}

有人能告诉我fun和fun1之间的区别吗?获得不同的输出!

c++ c recursion static
3个回答
1
投票
  1. static int n = 0;是一次初始化

像摘要一样,

    bool initialized = false;
    static int n;

    int fun1(int x){ 
       if(!initialized){
          n = 0;
          initialized = true;
       }
        if(x > 0){
            n++;
            return fun1(x-1)+n;
        }
        return 0;
    }
  1. static int n; n =0在每个递归调用中都重置为零。如下所示,
    bool initialized = false;
    static int n;
    int fun(int x){
       if(!initialized){
          n = 0;
          initialized = true;
       }
       n = 0;
        if(x > 0){
            n++;
            return fun(x-1)+n;
        }
        return 0;
    }

实际上n.BSS的一部分,并在加载时初始化为零。


0
投票

fun1中,每次调用该函数时,n都设置为0

fun中,n在程序启动时初始化为0,但此后仅由n++更新。


-1
投票

在fun1中,每当调用fun1时,您就使n = 0有趣的是,它将值重新获得为n ++,即仅将其初始化为0一次

© www.soinside.com 2019 - 2024. All rights reserved.