2

I'm quite curious about how a compiler physically evaluates constexpr functions at compile-time and I can't find relevant technical information.

  1. 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.?

  2. 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?

m.alessandrini
  • 317
  • 2
  • 9
  • Ok the sqrt example is not so meaningful because at run-time it would work with negative numbers, too (result is NaN). But at compile-time it's caught as invalid, I don't know why it's more strict there, maybe NaN is not a unique binary value. – m.alessandrini Nov 24 '21 at 09:32
  • If you only want to ge the flavour of the techniques used, you my want just to start with https://stackoverflow.com/questions/3082113/calculating-factorial-using-template-meta-programming and see what happen when you request a factorial of a negative number (run out the stack), then you may want to use std::enabled_if https://en.cppreference.com/w/cpp/types/enable_if to get a better error message than that. However, if you want to excatly see what gcc is doing you could look up the code. – Alessandro Teruzzi Nov 24 '21 at 10:20
  • @AlessandroTeruzzi interesting, are you suggesting that template meta-programming uses the same exact mechanics to evaluate stuff at compile-time? I didn't consider that. As for looking at the code, yes I could, but it's gcc, I think it would be a super-human feat if you're not well into it! – m.alessandrini Nov 24 '21 at 10:31

0 Answers0