简体   繁体   English

递归的默认返回值

[英]Default return value in recursion

Consider the following well known code to find factorial of a number. 考虑以下众所周知的代码来查找数字的阶乘。

int fact(int num)
{
    if (num != 1)
        return num * fact(num - 1);
    else
        return num;
}

Now consider one more variant of the same 现在考虑相同的另一个变体

int fact(int num)
{
    if (num != 1)
        return num * fact(num - 1);
}

The first one looks clean, and if we give num as 4, it'll be 4*3*2*1 . 第一个看起来很干净,如果我们给num作为4,它将是4*3*2*1 The second one is also working fine, even though compiler may give a warning. 即使编译器可能发出警告,第二个也可以正常工作。 But in the latter one, there's no return statement if the num become 1. So how the calculation happens? 但是在后一种情况下,如果num变为1,则没有return语句。那么计算如何进行? The code will work only when it return 1 if the num is 1. Can anybody please explain what's happening here 4*3*2*x . 该代码仅在num为1时返回1时才有效。有人可以解释一下4*3*2*x发生了什么。 How x is returned as 1. Thanks. x如何返回为1。谢谢。

Edit: I'm using gcc 4.8.2 编辑:我正在使用gcc 4.8.2

The second variant is incorrect, there is no such thing as "default return value", that behavior is totally undefined! 第二种错误是不正确的,没有“默认返回值”之类的东西,这种行为是完全不确定的!

Think about it, how will the compiler to know that fact(1) == 1 ?? 考虑一下,编译器将如何知道fact(1) == 1

If you let me guess, I'll say you wanted to avoid using the else stuff and, in that case, the default return value should be the last sentence. 如果让我猜测,我会说您想避免使用else东西,在这种情况下,默认的返回值应该是最后一句话。

int fact(int num)
{ // pre: num > 0
    if (num != 1)
        return num * fact(num - 1); 
    return num;
}

The second piece of code is incorrect, the warning that you thought is not important might be something like: 第二段代码不正确,您认为不重要的警告可能类似于:

warning: control reaches end of non-void function 警告:控制到达非无效功能的结尾

You must provide the return value in all paths, otherwise (when num is 1 ) it's undefined behavior, there's no default return value (with the exception of main ). 您必须在所有路径中提供返回值,否则(当num1 )是未定义的行为,没有默认的返回值main除外)。

It is an undefined behavior, which means that the result totally depends on the specific compiler. 这是未定义的行为,这意味着结果完全取决于特定的编译器。 Hence I think you should try to avoid it. 因此,我认为您应该避免这种情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM