I'm quite curious about how a compiler physically evaluates constexpr
functions at compile-time and I can't find relevant technical information.
I guess the code must be actually compiled to machine code and executed (interpretation should be out of question). Is that done in a sort of "sandboxed" environment, in another process with added interprocess code, etc.?
I tried as hard as I could to make a function crash at compile-time evaluation (invalid pointers, invalid function inputs, ...) but the compiler (gcc 11.2) always notices when an expression cannot be evaluated. Take for example:
#include <cmath>
constexpr int f(int a) {
return sqrt(a);
}
int main() {
constexpr int n = -3;
constexpr int p = f(n);
}
If n
is positive all is ok. If it's negative the compilation fails with:
error: ‘sqrt(-3.0e+0)’ is not a constant expression
How can it evaluate the validity of function inputs in the general case? (It could be much more complex than this). Perhaps it's first executed and if a run-time error is caught (during evaluation at compile-time) the expression is deemed as non valid as constant?