简体   繁体   中英

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 . 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? 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 . How x is returned as 1. Thanks.

Edit: I'm using 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 ??

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.

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 ).

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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