递归函数可以通过内联? [英] Can a recursive function be inline?

查看:689
本文介绍了递归函数可以通过内联?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

inline int factorial(int n)
{
    if(!n) return 1;
    else return n*factorial(n-1);
}

当我在读,发现上面code会导致无限汇编如果不通过编译器正确处理。

As I was reading this, found that the above code would lead to "infinite compilation" if not handled by compiler correctly.

编译器如何决定是否内联函数或不?

How does the compiler decide whether to inline a function or not ?

推荐答案

首先,在一个函数在线规范只是一个提示。编译器可以(而且经常)完全忽略了在线预选赛的presence与否。随着中说,一个编译器的可以的内联递归函数,就像它可以展开一个无限循环。它只是放置一个上限水平,它会展开功能。

First, the inline specification on a function is just a hint. The compiler can (and often does) completely ignore the presence or absence of an inline qualifier. With that said, a compiler can inline a recursive function, much as it can unroll an infinite loop. It simply has to place a limit on the level to which it will "unroll" the function.

这是优化编译器可能会将这个code:

An optimizing compiler might turn this code:

inline int factorial(int n)
{
    if (n <= 1)
    {
        return 1;
    }
    else
    {
        return n * factorial(n - 1);
    }
}

int f(int x)
{
    return factorial(x);
}

这个code:

int factorial(int n)
{
    if (n <= 1)
    {
        return 1;
    }
    else
    {
        return n * factorial(n - 1);
    }
}

int f(int x)
{
    if (x <= 1)
    {
        return 1;
    }
    else
    {
        int x2 = x - 1;
        if (x2 <= 1)
        {
            return x * 1;
        }
        else
        {
            int x3 = x2 - 1;
            if (x3 <= 1)
            {
                return x * x2 * 1;
            }
            else
            {
                return x * x2 * x3 * factorial(x3 - 1);
            }
        }
    }
}

在这种情况下,我们基本上是内联函数的3倍。一些编译器的的执行该优化。我记得MSVC ++有一个设置调整,将在递归函数(最多20个,我相信)进行内联的水平。

In this case, we've basically inlined the function 3 times. Some compilers do perform this optimization. I recall MSVC++ having a setting to tune the level of inlining that would be performed on recursive functions (up to 20, I believe).

这篇关于递归函数可以通过内联?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆