So, starting with C ++ 14, restrictions that have constexprdisappeared in C ++ 11, for example, the presence of new variables or loops in a function constexpr.
And the latest versions of the GCC and Clang compilers already support them.
So, the problem is that ... The function is constexprevaluated at compile time, and not at run time, if the value passed to it as a parameter is constant. So, the result of the function that I wrote below should appear instantly at runtime, right? But this is not so.
My question is: why is this happening? And do I have a misunderstanding of the C ++ 14 function constexpr? Thanks.
EDIT: Yes, I used -OO, so it will not work. But tuning -O1or a higher optimization speed does the trick, and the program runs as expected. Thank you all for your answers.
#include <iostream>
#include <chrono>
constexpr long long addition(long long num)
{
long long sum = 0;
for (int i = 0; i <= num; i++)
{
sum += i;
}
return sum;
}
int main()
{
auto start = std::chrono::steady_clock::now();
std::cout << addition(500000000);
auto stop = std::chrono::steady_clock::now();
auto dur = std::chrono::duration_cast<std::chrono::milliseconds>(stop - start);
std::cout << "\n\nIt took " << static_cast<double>(dur.count()) / 1000 << " seconds!";
std::cin.get();
}
source
share