So I was looking into stuff that can be done with constexpr variables and functions, and the jist I got was that if something is marked as constexpr, the compiler evaluates it and writes its values at compile-time instead of run-time.
Question: Is there an example of a case where something is marked as constexpr but the compiler chooses to not evaluate it at compile time? Or is that not possible?
Is there an example of a case where something is marked as constexpr but the compiler chooses to not evaluate it at compile time?
Yes, constexpr function will be evaluated in runtime if at least one argument is not avaliable in compile time:
1 2 3 4 5 6 7 8 9
constexprint foo(int i)
{ return i; }
//...
constexprint x = 10;
int y;
std::cin >> y;
constexprint x1 = foo(x); //foo(x) calculated in compile time, everything works fine
constexprint y1 = foo(y); //foo(y) cannot be calculated in compile time, line gives you an error as y1 is not initialized with compile-time constant
Still not quite sure what you mean, how is it possible for that function to be allowed to run at runtime? Like you said, it gives a compiler error on your line 9, and that's what I agree should happen. Can you give an example where it would compile but still be evaluated at run-time?
I'm just trying to figure out how strong the guarantee is that if something is marked constexpr, it has to be able to be evaluated at compile-time, or it's a compiler-time error.
gives a compiler error on your line 9, and that's what I agree should happen
It gives you an error because you are trying to assign it result to constexpr variable. If you do constexprint y1 = foo(y); , then it will compile and foo(y) will be evaluated at runtime.
Okay, part of me was hoping that it would be stricter, but I guess it makes sense from an implementation standpoint.
One more thing, just to be clear: For your example, once you get rid of the constexpr in y1, is x1 (and therefore foo(x) ) still able to be evaluated at compile-time even though y1 is now unable to?
Yes, foo(x) will be evaluated in compile time. constexpr functions are guaranteed to be evaluated at compile time if all arguments are compile time constants.
You can use templates to guarantee compile-time evaluation.