C++ 解释此C+中的程序流程+;功能

C++ 解释此C+中的程序流程+;功能,c++,C++,我写了一个奇怪的函数来求一个数的阶乘 int strange_fact(int n=0) { static int i=n; static int j=i; if(j>1) { i *= --j; strange_fact(); return 0x7777; //<------ This line } else return

我写了一个奇怪的函数来求一个数的阶乘

int strange_fact(int n=0)
{
    static int i=n;
    static int j=i;
    if(j>1)     
    {       
        i *= --j;
        strange_fact();         
        return 0x7777;    //<------ This line
    }
    else
        return i;
}
int奇怪的事实(int n=0)
{
静态int i=n;
静态int j=i;
如果(j>1)
{       
i*=-j;
奇怪的事实;

返回0x7777;//当对函数的递归调用结束时,将到达第9行。请参见以下(较短)示例:

因此,当调用foo(1)时,它将首先通过if(因为1>0)调用foo(0)。现在在这个调用中(foo(0))程序将进入else-barnch(因为0不是>0),foo(0)将返回0。所以现在我们将返回到我们的第一个调用(foo(1)),当foo(0)返回时,foo(1)将返回0x7777。

这一行

 strange_fact();
执行递归并丢弃结果

下一行

return 0x7777;
将最终返回该值


如果删除该行并使用警告进行编译,将通知您所有路径都不会返回值

,您需要了解递归是如何工作的

调用
strange\u fact()
后,您放置了一个return语句。这意味着一旦执行了函数,它仍将返回
0x7777
,这会把答案搞砸

检查此项,此项应按预期工作:

int strange_fact(int n=0)
{
    static int i=n;
    static int j=i;
    if(j>1)     
    {       
        i *= --j;
        strange_fact();         
        // return 0x7777;    // We don't want to return a value yet
    }
    if(j<=1)          // We need to check this condition after strange_fact is executed
        return i;

    // This line will never be executed
    return 0x7777;    //<------ This line
}
整个事情,用图表解释

让我们考虑<代码>奇怪的事实(3)< /代码>


因此,递归步骤中发生的任何事情都变得毫无意义,因为当控件返回到第一个调用时,
0x7777
最终将
return
ed。

Hm…iiuc调用堆栈中最内层的调用将在j次递归后返回(此处为1)。此时“this line”将在调用堆栈底部的最内层递归中执行,其他调用仍挂起。如果
J程序没有立即因堆栈溢出错误崩溃,则表明它在某个点从递归函数返回。递归调用不会神奇地结束原始调用。一旦递归调用ll已完成,您的程序将继续它停止的地方,就像任何函数调用一样…谢谢!虽然我知道这个概念,但它刚刚从我的脑海中消失。谢谢大家(您,@EdHeal和@gldraphael)的回答。+1ed所有答案!
int strange_fact(int n=0)
{
    static int i=n;
    static int j=i;
    if(j>1)     
    {       
        i *= --j;
        strange_fact();         
        // return 0x7777;    // We don't want to return a value yet
    }
    if(j<=1)          // We need to check this condition after strange_fact is executed
        return i;

    // This line will never be executed
    return 0x7777;    //<------ This line
}
long fact(long i)
{
    if(i > 0)
        return i * fact(i-1);
    if(i == 0)              // factorial(0) = 1
        return 1;

    throw exception("Negative numbers cannot have factorials"); // Or you can handle it by returning a -ve error code
}