Akshay CA
Akshay CA

Reputation: 53

Can't initialize constexpr value from return value of constexpr function

I am trying to understand how constexpr works. I am initializing a constexpr variable from the return value of a constexpr function as in the below code.

#include <iostream>

using namespace std;

constexpr size_t n = 40;

constexpr size_t Fib(const size_t n) {
    if (n <= 1) return n;
    return Fib(n - 1) + Fib(n - 2);
}

int main()
{
    //constexpr size_t Value = Fib(n);       // ----> Line 1
    const size_t Value = Fib(n);       // ----> Line 2
    cout << Value;
}

Line 1, if uncommented complains saying expression did not evaluate to a constant. However Line 2 works fine. What am I missing here?

Upvotes: 1

Views: 717

Answers (1)

D-RAJ
D-RAJ

Reputation: 3372

constexpr tells the compiler that it can be resolved at compile time, but does not guarantee it.

In Line 1, the compiler tries to resolve it at compile time. But the input is too large that the compiler fails to resolve it. The compiler output tells the full story.

# MSVC
> error C2131: expression did not evaluate to a constant
> message : failure was caused by evaluation exceeding step limit of 1048576 (/constexpr:steps<NUMBER>)

But in Line 2, the value does not need to be resolved at compile time, the compiler can let the CPU handle it at runtime. This is why Line 2 works without a hickup.

To further prove the point, try reducing the input value from 40, to something like 10. The compiler will resolve it without an issue.

Upvotes: 2

Related Questions