constexpr question, why do these two different programs run in such a different amount of time with g++?(constexpr 问题,为什么这两个不同的程序在 g++ 中运行的时间如此不同?)
问题描述
我正在使用 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.
这篇关于constexpr 问题,为什么这两个不同的程序在 g++ 中运行的时间如此不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:constexpr 问题,为什么这两个不同的程序在 g++ 中运行的时间如此不同?


- C语言详解float类型在内存中的存储方式 2023-03-27
- 详解C语言中sizeof如何在自定义函数中正常工作 2023-04-09
- C语言qsort()函数的使用方法详解 2023-04-26
- C语言手把手带你掌握带头双向循环链表 2023-04-03
- c++ const 成员函数,返回一个 const 指针.但是返回的指针是什么类型的 const? 2022-10-11
- Qt计时器使用方法详解 2023-05-30
- C++ 数据结构超详细讲解顺序表 2023-03-25
- 我应该为我的项目使用相对包含路径,还是将包含目录放在包含路径上? 2022-10-30
- Easyx实现扫雷游戏 2023-02-06
- ubuntu下C/C++获取剩余内存 2023-09-18