关于C ++中内联函数的两个问题 [英] Two questions about inline functions in C++

查看:168
本文介绍了关于C ++中内联函数的两个问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C ++中编译内联函数时有问题。

I have question when I compile an inline function in C++.

可以使用inline的递归函数。如果是,那么请描述如何。

Can a recursive function work with inline. If yes then please describe how.

我相信循环不能使用它,但我已经读某处递归将工作,如果我们传递常量值。

I am sure about loop can't work with it but I have read somewhere recursive would work, If we pass constant values.

我的朋友给我一些inline递归函数作为常量参数,并告诉我,这将工作,但不工作,我的笔记本电脑,在编译时没有错误,但在运行时显示没有,我必须终止它强制中断。

My friend send me some inline recursive function as constant parameter and told me that would be work but that not work on my laptop, no error at compile time but at run time display nothing and I have to terminate it by force break.

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

这是如何工作的?

我使用turbo 3.2

I am using turbo 3.2

此外,如果内联函数代码太大

Also, if an inline function code is too large then, can the compiler change it automatically in normal function?

推荐答案

这个特定的函数肯定可以内联。这是因为编译器可以知道这种特定形式的递归(尾递归)可以简单地变成正常循环。和一个正常的循环,它没有任何问题inlining它在所有。

This particular function definitely can be inlined. That is because the compiler can figure out that this particular form of recursion (tail-recursion) can be trivially turned into a normal loop. And with a normal loop it has no problem inlining it at all.

不仅可以编译器内联它,它甚至可以计算一个编译时常数的结果,生成函数的任何代码。

Not only can the compiler inline it, it can even calculate the result for a compile-time constant without generating any code for the function.

使用GCC 4.4

int fac = f(10); 

产生此指令:

movl    $3628800, 4(%esp)

程序集输出,该函数确实对输入是内联的,在编译时是未知的。

You can easily verify when checking assembly output, that the function is indeed inlined for input that is not known at compile-time.

这篇关于关于C ++中内联函数的两个问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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