constexpr问题,为什么这两个不同的程序运行在不同的时间与g ++? [英] constexpr question, why do these two different programs run in such a different amount of time with g++?
问题描述
我使用gcc 4.6.1,并得到一些有趣的行为涉及调用 constexpr
函数。这个程序运行很好,直接打印输出 12200160415121876738
。
include< iostream>
extern const unsigned long joe;
constexpr unsigned long fib(unsigned long int x)
{
return(x< = 1)? 1:(fib(x-1)+ fib(x-2));
}
const unsigned long joe = fib(92);
int main()
{
:: std :: cout< 这里我是!\\\
;
:: std :: cout<< joe<< '\\\
';
return 0;
}
这个程序永远运行,我从来没有耐心等待以便打印出一个值:
#include< iostream>
constexpr unsigned long fib(unsigned long int x)
{
return(x< = 1)? 1:(fib(x-1)+ fib(x-2));
}
int main()
{
:: std :: cout< 这里我是!\\\
;
:: std :: cout<<纤维(92) '\\\
';
return 0;
}
为什么会有这么大的差别?
编辑: g ++ -std =
解决方案 joe
是一个积分常数表达式;它必须可用于数组边界。因此,合理的编译器将在编译时对其进行评估。
在第二个程序中,即使编译器可以在编译时计算它,必须。
I'm using gcc 4.6.1 and am getting some interesting behavior involving calling a constexpr
function. This program runs just fine and straight away prints out 12200160415121876738
.
#include <iostream>
extern const unsigned long joe;
constexpr unsigned long fib(unsigned long int x)
{
return (x <= 1) ? 1 : (fib(x - 1) + fib(x - 2));
}
const unsigned long joe = fib(92);
int main()
{
::std::cout << "Here I am!\n";
::std::cout << joe << '\n';
return 0;
}
This program takes forever to run and I've never had the patience to wait for it to print out a value:
#include <iostream>
constexpr unsigned long fib(unsigned long int x)
{
return (x <= 1) ? 1 : (fib(x - 1) + fib(x - 2));
}
int main()
{
::std::cout << "Here I am!\n";
::std::cout << fib(92) << '\n';
return 0;
}
Why is there such a huge difference? Am I doing something wrong in the second program?
Edit: I'm compiling this with g++ -std=c++0x -O3
on a 64-bit platform.
解决方案 joe
is an Integral Constant Expression; it must be usable in array bounds. For that reason, a reasonable compiler will evaluate it at compile time.
In your second program, even though the compiler could calculate it at compile time, there's no reason why it must.
这篇关于constexpr问题,为什么这两个不同的程序运行在不同的时间与g ++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!