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.
编译器如何决定是否内联函数?
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.
编译器如何决定是否内联函数?
首先,函数的inline
规范只是一个提示.编译器可以(并且经常这样做)完全忽略inline
限定符的存在或不存在.如上所述,编译器can内联递归函数,就像它可以展开无限循环一样.它只需对其"展开"函数的级别进行限制即可.
优化编译器可能会将以下代码:
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次.一些编译器do执行这种优化.我记得MSVC++有一个设置,可以调整递归函数的内联级别(我相信最多20个).