c++ - 为什么以下代码中 "C"的值会发生变化?

标签 c++ c function recursion

the output I'm getting for the given code is "0" even though I initialized the value of c as "1"...can somebody explain it... Why is the value of "C" changing in the following code??

#include <iostream>

using namespace std;

int c=1; // global initialized 'c' as 1..

long long f(long long n){

    if(n==6){

        return 2;
    }

    else{   

        c=c+1;

        f(n-2);

    }

}
int main()
{
    long long n,ans,p;
    cin>>n;

    ans=f((2*n)-2);

    cout<<c; //printing out the value of 'c'
    return 0;
}

最佳答案

因为 c 的值在下面的代码中被更改:

else{       
        c=c+1;    
        f(n-2);    
    }

关于c++ - 为什么以下代码中 "C"的值会发生变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31168949/

相关文章:

c - 不理解字符计数程序的输出

c - 将非常量值传递给在 C 中采用 const 参数的函数的正确方法是什么

PHP - 设置 file_get_contents 超时

c++ - 较长的 sleep (在 C++ 中)不如短的精确

c++ - 检查字符串中每个字符的类型

c - 关于段错误的建议、有效使用 gdb、C 编程(新手)

javascript - 为什么这个简单的 javascript 函数不能完成它应该做的事情?

c++ - 如何检测 std::map 循环中的最后一次迭代?

c++ - 对多个源文件使用#define 一次

从主端更改伪 tty 回显模式