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

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

问题描述

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

正如我在阅读,发现如果没有由编译器正确处理,上面的代码将导致无限编译。

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 ?

推荐答案

$ c> inline 对一个函数的规范只是一个提示。编译器可以(通常)完全忽略是否存在 inline 限定符。这样,编译器可以内联递归函数,就像它可以展开无限循环一样。

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.

优化编译器可能会改变这个代码:

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);
}

加入此代码:

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天全站免登陆