I was reading Effective Modern C++ and wanted to try out a very basic function using constexpressions. My C++ skills are really not great, but I can't figure out what is wrong with this basic code:
constexpr int test( int x ) {
// works if: return x == 43337, otherwise segmentation fault
return x > 1000000 ? x+1 : test( x + 1 );
}
int main(int argc, char const *argv[])
{
constexpr auto x = 0;
cout << "Result: " << test( x );
return 0;
}
As mentioned in the comment, this code works if I use return x == 43337, but any larger value causes a segmentation fault.
What is wrong with this code? If I understand the constexpressions correctly, the computation should be on compilation, however it seems to me computation takes place during runtime. And larger values seems cause a segmentation fault, because the call stack gets too deep.
However, I'm not sure why I'm not receiving any compiler errors, since the computation should take place at compile time( apparently not ).
Additionally, would this code work if I the method signature looks like this:
constexpr decltype(auto) test( int x )
In your code, you are not calling test
in a context that requires compile time evaluation, and so the compiler is free to evaluate the call at run-time, leading to a segfault.
You could force a compile time context for the call to test
by using the result to initialize a constexpr
variable:
constexpr auto result = test( x ); // error
This gives a compile time error as expected:
error: constexpr variable 'result' must be initialized by a constant expression
constexpr auto result = test( x );
^ ~~~~~~~~~
note: constexpr evaluation exceeded maximum depth of 512 calls
...