I am using constexpr
to get the Fibonacci number
Enumeration is used to calculate the fibonacci in compile time
#include <iostream>
constexpr long fibonacci(long long n)
{
return n < 1 ? -1 :
(n == 1 || n == 2 ? 1 : fibonacci(n - 1) + fibonacci(n - 2));
}
enum Fibonacci
{
Ninth = fibonacci(9),
Tenth = fibonacci(10),
Thirtytwo = fibonacci(32)
};
int main()
{
std::cout << Fibonacci(Thirtytwo);
// std::cout << fibonacci(32);
return 0;
}
I am getting the following error on execution:
1>c:\users\hsingh\documents\visual studio 2017\projects\consoleapplication4\consoleapplication4\source.cpp(12): note: while evaluating 'fibonacci(30)' 1>c:\users\hsingh\documents\visual studio 2017\projects\consoleapplication4\consoleapplication4\source.cpp(6): note: while evaluating 'fibonacci(31)' 1>c:\users\hsingh\documents\visual studio 2017\projects\consoleapplication4\consoleapplication4\source.cpp(12): note: while evaluating 'fibonacci(31)' 1>c:\users\hsingh\documents\visual studio 2017\projects\consoleapplication4\consoleapplication4\source.cpp(12): error C2131: expression did not evaluate to a constant 1>c:\users\hsingh\documents\visual studio 2017\projects\consoleapplication4\consoleapplication4\source.cpp(5): note: failure was caused by control reaching the end of a constexpr function 1>c:\users\hsingh\documents\visual studio 2017\projects\consoleapplication4\consoleapplication4\source.cpp(12): note: while evaluating 'fibonacci(32)' 1>c:\users\hsingh\documents\visual studio 2017\projects\consoleapplication4\consoleapplication4\source.cpp(14): error C2057: expected constant expression 1>Done building project "ConsoleApplication4.vcxproj" -- FAILED.
But when I use run time int x=30, y=2; std::cout << fibonacci(x+y);//fibonacci is calculated on run time
I won't say I have a question but I have few confusions like:
- Is memory used by compile time and run time use of
constexpr
different? - How do I know where to stop exploiting or using compile time data?
- Which I am still trying to do is how to do Fibo-like calculation using both the advantage of compile time and run time together (use compile till it can be and after that let rest of calculation be done on run time).
Any example or reference if available will be helpful.