constexpr 问题,为什么这两个不同的程序在 g++ 中运行的时间如此不同?

2022-01-23 00:00:00 g++ c++ c++11 constexpr

我正在使用 gcc 4.6.1,并且遇到了一些有趣的行为,涉及调用 constexpr 函数.该程序运行良好,并立即打印出 12200160415121876738.

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!
";
   ::std::cout << joe << '
';
   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!
";
   ::std::cout << fib(92) << '
';
   return 0;
}

为什么会有这么大的差异?我在第二个程序中做错了吗?

Why is there such a huge difference? Am I doing something wrong in the second program?

我在 64 位平台上使用 g++ -std=c++0x -O3 进行编译.

I'm compiling this with g++ -std=c++0x -O3 on a 64-bit platform.

推荐答案

joe 是一个整型常量表达式;它必须在数组范围内可用.因此,合理的编译器会在编译时对其进行评估.

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.

相关文章