Is a constexpr value in C ++ (11) always guaranteed to be "computed" at compile time when assigned to a const var?

I wrote a deep recursive constexpr function that computes a lot. Although I assigned my return value something like this:

const int test = recursiveFunction(number);

      

I am sure that the value of my function is not computed at compile time, because my program happily compiles without errors or warnings, but if it fails, it will crash.

Hint: I realized that if this feature is not that deep (for example, when the number is "low"), the program works without problems.

+3


source to share


2 answers


To test this:

constexpr int recursiveFunction(int); // define somewhere

constexpr int number = 42; // or any other compile-time constant
constexpr int test = recursiveFunction(number);
static_assert(test == expected, ""); 

      



You might want to tweak the Clang compiler option -fconstexpr-depth=N

that sets the limit for recursive constexpr

function calls to N

. The default is 512. Another limit you can run is one -fconstexpr-steps

that has no documented default.

+3


source


The compiler can evaluate a constant expression at compile time if it chooses when run-time estimation will also be possible. However, an expression that exceeds an implementation limit, such as recursion depth constexpr

(or, as a consequence, undefined behavior) ceases to be a constant expression. The compiler then has to undo the evaluation and compile it for runtime. (It is possible that the run-time recursion would not have crashed. To prove that the function is indeed faulty, the halting problem will be solved.)



You can force compile-time evaluation by initializing a variable declared as constexpr

. This specifically disallows runtime initialization, so if constexpr

interrupted, you get a hard error.

+2


source







All Articles